Minimum Absolute Difference in BST

Easy

Topics
TreeDFSBST

Given the root of a Binary Search Tree, return the minimum absolute difference between the values of any two different nodes.

Example 1

12346
the closest pair
In a BST the closest pair of values is always adjacent in the in-order sequence, so only consecutive pairs need comparing — not all pairs. The shaded two differ by 1.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [4,2,6,1,3]
Output: 1

Example 2

01124849
the closest pair
Input:  root = [1,0,48,null,null,12,49]
Output: 1

Constraints

  • 2 <= number of nodes <= 10^4
  • 0 <= Node.val <= 10^5
  • The tree is a valid BST.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The brute force compares every pair of nodes, which is O(n^2). Collecting all values and sorting them is better at O(n log n) — but it throws away the one fact that makes this cheap.

An inorder traversal of a BST visits values in ascending order. In a sorted sequence the smallest difference between any two values is always between adjacent values, because any non-adjacent pair spans a gap that is at least as large. So one inorder walk, comparing each value to its immediate predecessor, finds the answer without sorting anything.

The implementation needs only one piece of carried state: the previously visited value. No array, no second pass.

Approach

  1. Inorder DFS, keeping previous (initially unset) and the running best.
  2. At each node, if previous exists, fold node.val - previous into the best, then set previous = node.val.

The subtraction needs no absolute value — inorder order guarantees the current value is the larger.

Dry Run

BST        4
          / \
         2   6
        / \
       1   3

inorder visits 1, 2, 3, 4, 6

prev=none  node=1              best=inf   prev=1
prev=1     node=2  diff 1      best=1     prev=2
prev=2     node=3  diff 1      best=1     prev=3
prev=3     node=4  diff 1      best=1     prev=4
prev=4     node=6  diff 2      best=1     prev=6

answer 1

Complexity

  • Time — O(n): each node visited once. Against O(n log n) for collect-and-sort and O(n^2) for all pairs.
  • Space — O(h): the recursion stack only, where h is the height — O(log n) balanced, O(n) on a degenerate chain. Collecting values into an array would be O(n) regardless of shape.

Common Pitfalls

  • Comparing a node against its parent or its children instead of its inorder predecessor. The closest value is adjacent in sorted order, which is not the same as adjacent in the tree.
  • Initialising previous to 0. Values can be 0, so a sentinel of None is needed to detect the first node.
  • Forgetting that the traversal must be inorder. Pre- or post-order visits values out of sequence and the adjacency argument collapses.
  • Collecting all values just to sort them, which discards the BST property the problem is testing.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def getMinimumDifference(self, root):
        self.prev = None; self.best = float("inf")
        def inorder(node):
            if not node: return
            inorder(node.left)
            if self.prev is not None:
                self.best = min(self.best, node.val - self.prev)
            self.prev = node.val
            inorder(node.right)
        inorder(root)
        return self.best
SensAI
Beta
Tap the mic to stop voice mode