C++ concise solution with O(1) space.


  • 0
    H
    class Solution {
    public:
        TreeNode* upsideDownBinaryTree(TreeNode* root) {
            TreeNode *left = nullptr;
            TreeNode *right = nullptr;
            TreeNode *node = root;
            TreeNode *head = nullptr;
            while (node) {
                swap(node->left, right);
                swap(node->right, left);
                swap(node->left, node->right);
                // move to next.
                head = node;
                swap(node, right);
            }
            return head;
        }
    };

Log in to reply
 

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