C++ recursive version only 19 lines


  • 0
    C
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* upsideDownBinaryTree(TreeNode* root) {
            return helper(root, NULL);
        }
        TreeNode* helper(TreeNode *root, TreeNode *parent) {
            if (!root)
                return NULL;
            if (!root->left && !root->right) {
                root->left = parent ? parent->right : NULL;
                root->right = parent;
                return root;
            }
            TreeNode *left = helper(root->left, root);
            root->left = parent ? parent->right : NULL;
            root->right = parent;
            return left;
        }
    };
    

Log in to reply
 

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