Minimum Absolute Difference in BST
Easy
Topics
Given the root of a Binary Search Tree, return the minimum absolute difference between the values of any two different nodes.
Example 1
null marks a missing child.Input: root = [4,2,6,1,3] Output: 1
Example 2
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
- Inorder DFS, keeping
previous(initially unset) and the running best. - At each node, if
previousexists, foldnode.val - previousinto the best, then setprevious = 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 1Complexity
- 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
his 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
previousto 0. Values can be 0, so a sentinel ofNoneis 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.bestimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int getMinimumDifference(TreeNode root) {
prev = 0;
has = false;
best = Integer.MAX_VALUE;
inorder(root);
return best;
}
long prev;
boolean has;
int best;
private void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
if (has) best = Math.min(best, (int)(node.val - prev));
prev = node.val;
has = true;
inorder(node.right);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int getMinimumDifference(TreeNode* root) {
long long prev = 0;
bool has = false;
int best = INT_MAX;
function<void(TreeNode*)> inorder = [&](TreeNode* node) {
if (!node) return;
inorder(node->left);
if (has) best = min(best, (int)(node->val - prev));
prev = node->val;
has = true;
inorder(node->right);
};
inorder(root);
return best;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var getMinimumDifference = function(root) {
let prev = null, best = Infinity;
const inorder = (node) => {
if (!node) return;
inorder(node.left);
if (prev !== null) best = Math.min(best, node.val - prev);
prev = node.val;
inorder(node.right);
};
inorder(root);
return best;
};