Doubt about the recursive method


  • 0
    Y
    I just want to try the recursive method but the results was rather upset.
    I used a static vector to implement the recursive progress,but the outcome was strange.
    
    here is my code:
    vector<int> inorderTraversal(TreeNode* root) 
    {
        static vector<int> t;
        if(root)
        {
            inorderTraversal(root->left);
            t.push_back(root->val);
            inorderTraversal(root->right);
        }
        return t;
    }
    

    when input is [1,2],the expected output is [2,1],but the actual output was [1,2,1],I wonder why there's a "1" at the front? Help!


  • 2

    Your solution is tested with more than one test case, and since you made t static, you'll always use the same vector. That extra 1 is still in there from a previous test case.


  • 0
    L

    Thank you for your reply! I have the same question.


Log in to reply
 

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