C++, 3ms, simple recursion


  • 0
    T
    
        void upsideDownBinaryTreeHelper(TreeNode* root, TreeNode*& new_root)
        {       
             if( !root ) 
                 return;
            
             if(!root->left)
             {
                 if(!new_root)
                     new_root = root;
                 return;
             }       
            
            upsideDownBinaryTreeHelper(root->left, new_root);
    
            root->left->right = root;
            root->left->left = root->right;       
            root->left = nullptr;
            root->right = nullptr; 
            
        }
        
        TreeNode* upsideDownBinaryTree(TreeNode* root) {
            TreeNode* curr = nullptr;
            upsideDownBinaryTreeHelper(root,curr);  
            return curr;
        }
    
    

Log in to reply
 

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