Doubt in my AC C++ solution.


  • 0
    C
    /**
    * Definition for a binary tree node.
    * struct TreeNode {
    *     int val;
    *     TreeNode *left;
    *     TreeNode *right;
    *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    * };
    */
    
    class Solution {
    public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL)return root;
        invertTree(root->left);            // 1
        invertTree(root->right);          //  2
        swap(root->left,root->right);
        return root;
       }
    };
    

    I got this accepted in 0 ms but I don't get how swapping between left child and right child pointers after two recursion works fine in my case.I have seen people doing similar swapping before the two recursive statements(1& 2).So which one is correct.I think I was lucky to get AC.

    Please let me know which one is correct solution.And also how can I cross check my own solution for problems like this.Thanks in advance.


Log in to reply
 

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