My C++ iterative solution


  • 0
    T
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr)
            return nullptr;
        
        std::stack<TreeNode*> stk;
        stk.push(root);
        
        while (!stk.empty()) {
            TreeNode *node = stk.top();
            stk.pop();
            
            std::swap(node->left, node->right);
            if (node->left != nullptr)
                stk.push(node->left);
            if (node->right != nullptr)
                stk.push(node->right);
        }
        
        return root;
    }

Log in to reply
 

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