Easy C++ solution


  • -2
    O
    /*
        The idea is to use three pointers to manage the current TreeNodes
        
        use nextLeft and nextRight for tree traversal
    */
    
    TreeNode* upsideDownBinaryTree(TreeNode* root) 
    {
        if(root == NULL)
            return root;
            
        TreeNode* cur = root;
        TreeNode* curLeft = root->left;
        TreeNode* curRight = root->right;
        TreeNode* nextLeft = NULL;
        TreeNode* nextRight = NULL;
        
        
        while(curLeft != NULL)
        {
            nextLeft = curLeft->left;
            nextRight = curLeft-right;
            
            curLeft->left = curRight;
            curLeft->right = cur;
            
            cur->left = NULL;       cur->right = NULL;
            cur = curLeft;
            
            curLeft = nextLeft;
            curRight = nextRight;
        }
        
        return cur;
    }

  • 1
    J

    You code is wrong. The right and left children of "cur" can only be set to "nullptr" if "cur" is root.
    Instead of
    cur ->left = NULL;
    cur->right = NULL;

    You should do:
    if(cur == root){
    cur->left = NULL;
    cur->right = NULL;
    }


Log in to reply
 

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