Easy to understand neat Java solution.


  • 0
    P
    public class Solution {
        TreeNode master = null;
        
        public TreeNode upsideDownBinaryTree(TreeNode root) {
            dfs(root);
            return master;
            
        }
        public TreeNode dfs(TreeNode root) {
            if(root == null)
                return null;
            TreeNode node = dfs(root.left);
            if(master == null && node == null)
                master = root;
            if(node != null) {
                node.left = root.right;
                node.right = root;
            }
            root.left = null; root.right = null;
            return root;
        }
    }
    

Log in to reply
 

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