Both C++ recursive and non-recursive solution


  • 0
    G

    Non-recursive solution

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

    Recursive solution

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            if (root){
                invertTree(root->left);
                invertTree(root->right);
                swap(root->left,root->right);
            }           
            return root; 
        }
    };
    

Log in to reply
 

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