Simple C++ solution (recursive and iterative)


  • 3
    J

    1.Recursive

    TreeNode* invertTree(TreeNode* root) {
        if(!root) return NULL;
        swap(root->left, root->right);
        root->left = invertTree(root->left);
        root->right = invertTree(root->right);
        return root;
    }
    

    2.Iterative

    TreeNode* invertTree(TreeNode* root) {
        if(!root) return NULL;
        queue<TreeNode*> q; q.push(root);
        while(!q.empty()) {
            TreeNode* t = q.front(); q.pop();
            swap(t->left, t->right);
            if(t->left) q.push(t->left);
            if(t->right) q.push(t->right);
        }
        return root;
    }

  • 0

    Clear and elegant solutions!


Log in to reply
 

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