Very straightforward traversal solution [Java]


  • 0
    T
    int min = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        helper(root);
        return min;
    }
    private void helper(TreeNode root){
        if(root.left == null && root. right == null){
            return;
        }
        if(root.left != null){
            min = Math.min(min, Math.abs(root.val - findMax(root.left).val));
            helper(root.left);
        }
        if(root.right != null){
            min = Math.min(min, Math.abs(root.val - findMin(root.right).val));
            helper(root.right);
        }
        
    }
    private TreeNode findMin(TreeNode root){
    	while(root.left != null){
    		root = root.left;
    	}
    	return root;
    }
    private TreeNode findMax(TreeNode root){
    	while(root.right != null){
    		root = root.right;
    	}
    	return root;
    }

Log in to reply
 

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