Java Straightforward Method


  • 0
    Z
    public class Solution {
        int min = Integer.MAX_VALUE;
        TreeSet<Integer> treeSet = new TreeSet<>();
        public int getMinimumDifference(TreeNode root) {
            if (root == null) return 0;
            fstTraverse(root);
            return min;
        }
        
        void fstTraverse(TreeNode curr) {
            if (curr == null) return;
            Integer left = treeSet.floor(curr.val);
            if (left != null) min = Math.min(min, curr.val-left);
            Integer right = treeSet.ceiling(curr.val);
            if (right != null) min = Math.min(min, right-curr.val);
            treeSet.add(curr.val);
            fstTraverse(curr.left);
            fstTraverse(curr.right);
        }
    }
    

Log in to reply
 

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