Skip to content
Problem 530 · LeetCode 530(opens in a new tab)

Minimum Absolute Difference in BST

EasyBinary search trees

You get root, the top of a binary search tree: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger.

Look at every pair of different nodes and the gap between their values. Return the smallest such gap.

Example 1

Input:  root = [10, 4, 15, 2, 7]
Output: 2
Why:    4 and 2 are two apart; no pair is closer
2 more examples and the constraints

Example 2

Input:  root = [50, 40, 90, null, 49]
Output: 1
Why:    49 and 50 sit two levels apart but differ by 1

Example 3

Input:  root = [0, null, 100000]
Output: 100000
Why:    only one pair

Constraints

  • 2 ≤ number of nodes ≤ 10,000
  • 0 ≤ each node value ≤ 100,000
  • The tree is a valid binary search tree, so values are distinct

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every pair of valuesO(n²)
  2. In-order walk, compare neighboursO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
Every pair of valuesO(n²)
Mention it, then move on
In-order walk, compare neighboursO(n)
Best; one walk

n = number of nodes, h = height of the tree.

Edge cases to test

  • Two nodes. [0, null, 100000] has one pair; return its gap.
  • Closest pair far apart in the tree. In [50, 40, 90, null, 49], 49 and 50 are not parent and child. Comparing only parents and children misses it.
  • A long chain. A tree that is one straight line is 10,000 levels deep; recursion can overflow, the stack does not.
  • Value 0. Do not treat 0 as "no previous value"; use a separate marker such as −1 or None.

Common mistakes

  • Comparing each node only with its children, which misses neighbours across levels.
  • Using 0 as the "no previous value" marker, though 0 is a valid node value.
  • Walking pre-order or level-order, which does not give sorted order.

How to talk through it

  1. 1Clarify. Is it a valid search tree? Can values repeat? Are there at least two nodes?
  2. 2Give the brute force. Collect every value and try every pair. Say it is O(n²) and ignores the tree.
  3. 3Use the order. In-order gives sorted values, and the closest pair in a sorted list is adjacent.
  4. 4Code the walk. Stack-based in-order, keep prev and best, compare on each pop.
  5. 5Test out loud. Run two nodes, the cross-level case and a chain before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?