My simple recursion solution in c++


  • 1

    Adding (root->left!=NULL || root->right!=NULL) judgement to improve efficiency from 6ms to 0ms

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            TreeNode* tmp;
            if(root!=NULL && (root->left!=NULL || root->right!=NULL)){//do not forget root==NULL
                tmp = root->left;
                root->left = root->right;
                root->right = tmp;
    //above three lines can be written in std::swap(root->left, root->right);
                invertTree(root->left);
                invertTree(root->right);
            }
            return root;
        }
    };
    

  • 0

    Awesome. If you use markdown to present your code, it would be better.


  • 0

    @boyzhirui just change it : ) thank you>.<


Log in to reply
 

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