Share my nonrecursive C++ solution.


  • 1
    A
    TreeNode* invertTree(TreeNode* root) {  
        stack<TreeNode *> s;
        TreeNode *p=root;
        while(p!=NULL||!s.empty())
        {
            while(p!=NULL)
            {
                swap(p->left, p->right);
                s.push(p);
                p=p->left;
            }
                p=s.top();
                s.pop();                          
                p=p->right;        
    
        }
        return root;
    
        }

  • 0
    B

    excellent solution.
    I tried to bfs the tree, use an array to save nodes, then create a new tree.
    That's horible.


Log in to reply
 

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