Recursive Java solution

  • 6
    public class Solution {
        public TreeNode UpsideDownBinaryTree(TreeNode root) {
            if(root == null)return null;
            if(root.left == null)return root;
            TreeNode newroot = UpsideDownBinaryTree(root.left);
            root.left.left = root.right;
            root.left.right = root;
            root.right = null;
            root.left = null;
            return newroot;

    The leftmost node is the new root. The key is to go down along the leftmost path to find the new root and reset all pointers when poping up.

Log in to reply

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