Minimum Distance Between BST Nodes (LeetCode 783): Solution and Explanation

Easy
Tree
Depth First search
Breadth First search
Binary search tree
Binary tree

Given the root of a binary search tree, return the smallest difference between the values of any two different nodes.

Intuition

Comparing every pair of nodes works but takes O(n^2). The structure of the problem gives a shortcut: if you sort a set of numbers, the closest pair is always two neighbours in that sorted list. Any pair that skips over a value is at least as far apart as one of the neighbour pairs inside it.

A BST already stores its values in sorted order; an inorder traversal reads them out smallest first. So walk the tree inorder, remember the last value you saw, and check the gap each time a new value comes out.

Doing the inorder walk with an explicit stack makes the order visible: slide down the left edge pushing nodes, pop the top (the next smallest value), compare it with the previous one, then continue from its right child.

Approach: Iterative inorder with a previous value

  1. Start with an empty stack, node = root, prev = None and best = infinity.
  2. While node is not null, push it and move to node.left.
  3. Pop the top of the stack. It is the next value in sorted order.
  4. If prev exists, set best = min(best, node.val - prev). The difference is never negative because values come out increasing.
  5. Set prev = node.val and node = node.right, and repeat while the stack or node is non-empty.

Step-by-step example

root = [4,2,6,1,3]
  1. Push 4, 2, 1 down the left edge. Pop 1: it is the smallest value, prev = 1.
  2. Pop 2. Gap 2 - 1 = 1, best = 1. Move to 2's right child 3.
  3. Push 3, pop 3. Gap 3 - 2 = 1, best stays 1.
  4. Pop 4. Gap 4 - 3 = 1. Move to the right child 6, push and pop it. Gap 6 - 4 = 2.
  5. The stack is empty and node is null. Return 1.

Code: Python, Java, C++

1class Solution:
2    def minDiffInBST(self, root: Optional[TreeNode]) -> int:
3        stack = []
4        node = root
5        prev = None
6        best = float('inf')
7        while stack or node:
8            while node:
9                stack.append(node)
10                node = node.left
11            node = stack.pop()
12            if prev is not None:
13                best = min(best, node.val - prev)
14            prev = node.val
15            node = node.right
16        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Iterative inorder with a previous value O(n)
Recursive inorder O(n)
Morris inorder O(n)
Collect and sort O(n log n)
Time

O(n)

Every node is pushed once and popped once, and each pop does O(1) work.

Space

O(h)

The stack holds at most one root-to-leaf path, so its size is the tree height h. That is O(log n) for a balanced tree and O(n) for a chain.

Other approaches

Recursive inorder (time O(n), space O(h))

Same idea with recursion instead of an explicit stack, keeping prev and best in outer variables. Shorter, uses the call stack.

Collect and sort (time O(n log n), space O(n))

Gather every value with any traversal, sort the list, and scan neighbouring pairs. Ignores the BST property but works on any binary tree.

Morris inorder (time O(n), space O(1))

Temporarily thread each predecessor's right pointer back to the current node, so the traversal needs no stack at all. The tree is restored as the walk proceeds.

Common mistakes

  • Comparing each node only with its parent and children. The closest pair can be far apart in the tree, for example a node and the leftmost node of its right subtree.
  • Comparing the first value with a sentinel such as 0 or -1 that could create a fake small gap. Skip the comparison until a real previous value exists.
  • Using preorder or level order. Only inorder gives sorted values, which is what makes neighbour comparison enough.

Frequently asked questions

Is this the same problem as Minimum Absolute Difference in BST (LeetCode 530)?

Yes. The two problems have the same statement and the same solution; only the constraints differ slightly. This page shows the iterative stack version, while the 530 page uses recursion.

Why is it enough to compare neighbours in sorted order?

For sorted values a < b < c, c - a = (c - b) + (b - a), which is at least as big as either neighbour gap. So the closest pair never skips over a value.

Why can the difference be computed without abs()?

Inorder traversal of a BST gives increasing values, so node.val is always larger than prev and the difference is already positive.