AlgoMaster Logo

Minimum Distance Between BST Nodes

tree=[4, 2, 6, 1, 3]
1public int minDiffInBST(TreeNode root) {
2    int minDiff = Integer.MAX_VALUE;
3    Integer prev = null;
4    Stack<TreeNode> stack = new Stack<>();
5    TreeNode current = root;
6
7    while (!stack.isEmpty() || current != null) {
8        // Go to leftmost node
9        while (current != null) {
10            stack.push(current);
11            current = current.left;
12        }
13
14        // Visit node
15        current = stack.pop();
16
17        // Calculate difference with previous
18        if (prev != null) {
19            minDiff = Math.min(minDiff, current.val - prev);
20        }
21
22        // Update prev to current value
23        prev = current.val;
24
25        // Move to right subtree
26        current = current.right;
27    }
28
29    return minDiff;
30}
0 / 51
minDiff:nullprev:null42613Stack