Java Recursive Solution - Not Using a Global Variable (16ms)


  • 0
    A
    class Solution
    {
        public int getMinimumDifference(TreeNode root)
        {
            if(root == null)    return Integer.MAX_VALUE;
            
            int v1 = (root.left  != null) ? root.val - rightmost(root.left) : Integer.MAX_VALUE;
            int v2 = (root.right != null) ? leftmost(root.right) - root.val : Integer.MAX_VALUE;
            int v3 = getMinimumDifference(root.left);
            int v4 = getMinimumDifference(root.right);
                
            return Math.min(Math.min(v1, v2), Math.min(v3, v4));
        }
    
        private Integer leftmost(TreeNode root)
        {
            if(root == null)    return null;
            
            while(root.left != null)
                root = root.left;
            
            return root.val;
        }
        
        private Integer rightmost(TreeNode root)
        {
            if(root == null)    return null;
            
            while(root.right != null)
                root = root.right;
            
            return root.val;
        }
        
    }
    

Log in to reply
 

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