Invert binary tree c++ 0ms simple solution


  • 0
    P
    class Solution {
    public:
    
        using Stack = stack<TreeNode*>;
    
        TreeNode* invertTree(TreeNode* root) {
            
            if(root)
            {
                Stack pool;
                pool.push(root);
                
                while(!pool.empty())
                {
                    auto n = pool.top();
                    pool.pop();
                    
                    auto tmp = n->left;
                    n->left = n->right;
                    n->right = tmp;
                    
                    if(n->left)
                        pool.push(n->left);
                    
                    if(n->right)
                        pool.push(n->right);
    
                }
            }
            
            return root;
        }
    };

Log in to reply
 

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