Another JavaScript solution


  • 0

    The problem description is a bit unclear, maybe there should be more examples, if I understand correctly, for this problem, any right child node can either be a leaf node or null, which means, any right child node cannot have any child.

    So let's do a "half" postorder traversal and tweak the left and right pointers bottom up to the root node, and obviously, the leftmost child is our new root.

    /**
     * @param {TreeNode} root
     * @return {TreeNode}
     */
    var upsideDownBinaryTree = function(root) {
        if (!root || !root.left && !root.right) {
            return root;
        }
        
        var newRoot = upsideDownBinaryTree(root.left);
        
        root.left.left = root.right;
        root.left.right = root;
        
        root.left = null;
        root.right = null;
        
        return newRoot;
    };
    

Log in to reply
 

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