Why my solution get wrong answer ??


  • 0
    M
      void rightSideViewUtil(TreeNode* root,vector<int> & A) {
            if(root == NULL)
            return;
            A.push_back(root->val);
            if(root->right== NULL)
            rightSideViewUtil(root->left, A);
            else
            rightSideViewUtil(root->right, A);
        }
        vector<int> rightSideView(TreeNode* root) {
    		vector<int> A;
             rightSideViewUtil(root,A);
             return A;
        }
    

    for this test case
    Input: [1,2,3,4]

    Output: [1,3]

    Expected: [1,3,4]


  • 0

    If you want others to read your code, it would be good to indent it properly.


  • 0
    M

    Thanks for your advice :)


  • 1
    M

    i figured out why it goes wrong!

    if i go to right child i will not check left child from being processed at all.

    for this below tree. my code will produce [1,3] only.

     1
    / \3
    2
     \
      4 
    

    and here is a correction of my code.

    simply i should go to the right and left. and keep track of inserted items.

    accepted solution:

     void rightSideViewUtil(TreeNode* root,vector<int> & A,int level) {
            if(root == NULL)
            return;
            if(A.size()<=level)
            A.push_back(root->val);
            rightSideViewUtil(root->right, A,level+1);
            rightSideViewUtil(root->left, A,level+1);
        }
        vector<int> rightSideView(TreeNode* root) {
    		vector<int> A;
             rightSideViewUtil(root,A,0);
             return A;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.