Concise JAVA Traversal (not In-order ), time O(n),


  • 0

    For any node, current Minimum Absolute Difference is (min value of right - current value) or (current value - max value of left).

        public int res = Integer.MAX_VALUE;
        public int getMinimumDifference(TreeNode root) {
            travel(root);
            return res;
        }
        
        public int[] travel(TreeNode root) {
            int max = root.val, min = root.val;
            if(root.left != null) {
                int[] left = travel(root.left);
                min = left[1];
                res = Math.min(res, root.val - left[0]);
            }
            if(root.right != null) {
                int[] right = travel(root.right);
                max = right[0];
                res = Math.min(res, right[1] - root.val);
            }
            
            return new int[]{max, min};
        }
    

Log in to reply
 

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