Problem 783 · LeetCode 783(opens in a new tab)
Minimum Distance Between BST Nodes
EasyBinary search trees
You are given root, the root of a binary search tree. In such a tree, every value in a node's left subtree is below the node's value and every value in its right subtree is above it.
Pick any two different nodes and take the difference of their values. Return the smallest difference you can get.
Example 1
Input: root = [9, 4, 15, 2, 8] Output: 1 Why: 8 and 9 differ by 1, though 8 is a grandchild of 9
2 more examples and the constraints
Example 2
Input: root = [20, 10, 30, null, 18, 27] Output: 2 Why: sorted the values are 10, 18, 20, 27, 30; 18 to 20 is the smallest step
Example 3
Input: root = [5, 1] Output: 4 Why: two nodes, one pair
Constraints
- 2 ≤ number of nodes ≤ 100
- 0 ≤ each node value ≤ 100,000
- The tree is a valid binary search tree, so no two values are equal
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Compare every pairO(n²)
- In-order walk with prevO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 nodes | Verdict |
|---|---|---|---|
| Compare every pair | O(n²) | Correct but ignores the order | |
| In-order walk with prev | O(n) | Best; one pass |
n = number of nodes, h = height of the tree.
Edge cases to test
- Only two nodes. [5, 1] has a single pair; return its difference, 4.
- Closest pair is not parent and child. In [9, 4, 15, 2, 8], 8 and 9 are two levels apart. Checking only parent and child edges misses them.
- A value of 0. 0 is a real value, so do not use 0 to mean "no previous value".
- A tree that is one long line. [2, null, 7, null, 13, null, 14] is a chain; the stack still holds at most the path.
- Far apart values. [0, null, 100000] returns 100,000.
Common mistakes
- Comparing each node only with its direct children, which misses neighbours in sorted order that are several levels apart.
- Starting
prevat 0, so a tree containing small values produces a false tiny gap. - Using pre-order or level-order, which do not visit the values in sorted order.
How to talk through it
- 1Clarify. Is the tree a valid search tree? Can values repeat? Are there always at least two nodes?
- 2Give the brute force. Gather all values and compare every pair: O(n²), and it ignores the tree's order.
- 3Use the order. In-order reads values sorted, and in sorted order the closest pair is adjacent.
- 4Code the walk. Iterative in-order with a stack; track
prevandbeston each pop. - 5Test out loud. Try two nodes, the cross-level pair in Example 1 and a one-sided chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?