C# No extra space Accepted solution


  • 0
    J

    While traversing through the tree, we rearrange the nodes. The stack memory will act as the stack, to get the parent nodes

    public TreeNode UpsideDownBinaryTree(TreeNode root) 
        {
            if (root == null) return root;
            if (root.left == null && root.right == null) return root;
        
            Helper(root);
            root.left = null;
            root.right = null;
            return newroot;
        }
        
        TreeNode newroot = new TreeNode(0);
        
        private void Helper(TreeNode root)
        {
            if (root.left == null && root.right == null)
            {
                newroot = root;
                return;
            }
            
            Helper(root.left);
            root.left.left = root.right;
            root.right = null;
            root.left.right = root;
            return;
        }
    

Log in to reply
 

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