1ms Java Solution - using recur

  • 0
       public TreeNode upsideDownBinaryTree(TreeNode root) {
            if (null == root){
                return null;
            return helper2(root);
        public TreeNode helper2(TreeNode node){
            if (null == node){
                return null;
            TreeNode left = helper2(node.left);
            TreeNode right = helper2(node.right);
            // only check left, if left is null, then right is also null
            // but if left is not null, then right may or may not be null
            if (null != left){
                // the leftmost node is the root
                // if left is not null, then keep passing the left node
                // as the root node.
                TreeNode result = left;
                TreeNode cur = result;
                // This is important to node
                // go all the way to the right to
                // reach the current left.
                while (null != cur.right){
                    cur = cur.right;
                cur.right = new TreeNode(node.val);
                if (null != right){
                    cur.left = right;
                return result;
            }else {
                // if left is null, then right is also null.
                // So its a left node, pass it through
                return node;

Log in to reply

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