Skip to content

Minimum Absolute Difference in BST

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

InputOutputExplanation
Tree: 4, 2→1, 2→3, 61Sorted values: [1, 2, 3, 4, 6]. Min diff = 2 - 1 = 1
Tree: 1, 0, 48→24, 48→null24Sorted values: [0, 1, 24, 48]. Min diff = 24 - 0 = 24
  • The number of nodes in the tree is in the range [2, 10^4].
  • 0 <= Node.val <= 10^5
  • All the values of the tree are unique.
ApproachTimeSpaceKey IdeaBest When
In-Order DFSO(n)O(h)Visit nodes in sorted order; compare adjacent pairs onlyGeneral case — standard BST usage
BFS Level-OrderO(n log n)O(w)Collect all values, sort, then find min diffTree structure unknown or comparison required
  • Pick In-Order DFS if you want the most elegant and efficient solution.
  • Pick BFS Level-Order if you prefer a simpler mental model (collect all, sort, compare).
Best For Speed
In-Order DFS
O(n) time · O(h) space
Simpler Mental Model
BFS Level-Order
O(n log n) time · O(w) space
★ Recommended

Traverse the BST in in-order (left → node → right), which visits nodes in ascending sorted order. As you visit each node, compare its value with the previously visited value. The minimum difference must occur between two consecutive values in this sorted sequence.

⏱ Time O(n) Single pass 💾 Space O(h) Recursion stack

Input: Tree with values [4, 2, 6, 1, 3]

StepNodeprevDiffmin_diffAction
11nullFirst node, store prev = 1
2212 - 1 = 11Update min_diff = 1
3323 - 2 = 11min_diff = 1
4434 - 3 = 11min_diff = 1
5646 - 4 = 21min_diff stays 1

Animated walkthrough

How in-order DFS finds the minimum difference

Watch the in-order traversal visit nodes in sorted order, comparing each node with its previous neighbor.

Step 1 of 3 Target: 1
Waiting to begin...
Array state
Memory / lookup state

function getMinimumDifference_inorder(root):
min_diff = infinity
prev = null
function inorder(node):
if node is null:
return
inorder(node.left)
// Visit node
if prev is not null:
min_diff = min(min_diff, node.val - prev)
prev = node.val
inorder(node.right)
inorder(root)
return min_diff
minimum_absolute_difference_in_bst_inorder.py
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def get_minimum_difference_inorder_dfs(root: Optional[TreeNode]) -> int:
"""
In-order DFS approach to find minimum absolute difference in BST.
In a BST, in-order traversal yields sorted values.
We track the previous value and compute differences.
Time: O(n) - visit each node once
Space: O(h) - recursion stack, h = height
"""
min_diff = [float('inf')]
prev = [None]
def inorder(node):
if not node:
return
# Traverse left subtree
inorder(node.left)
# Process current node
if prev[0] is not None:
min_diff[0] = min(min_diff[0], node.val - prev[0])
prev[0] = node.val
# Traverse right subtree
inorder(node.right)
inorder(root)
return min_diff[0]
# Test cases
if __name__ == "__main__":
# Example 1: BST with multiple nodes
root1 = TreeNode(4)
root1.left = TreeNode(2)
root1.right = TreeNode(6)
root1.left.left = TreeNode(1)
root1.left.right = TreeNode(3)
print(get_minimum_difference_inorder_dfs(root1)) # 1
# Example 2: Single path
root2 = TreeNode(1)
root2.right = TreeNode(5)
root2.right.left = TreeNode(4)
print(get_minimum_difference_inorder_dfs(root2)) # 1
🎯 Interview Favourite

Perform a level-order (breadth-first) traversal to collect all node values, sort them, then iterate through consecutive pairs to find the minimum difference.

This approach trades O(n log n) time for a simpler, more straightforward algorithm that does not rely on understanding BST properties.

⏱ Time O(n log n) Sorting overhead 💾 Space O(w) Queue + values

Input: Tree with values [4, 2, 6, 1, 3]

  1. BFS Traversal: Collect [4, 2, 6, 1, 3]
  2. Sort: [1, 2, 3, 4, 6]
  3. Find min diff between consecutive pairs:
    • 2 - 1 = 1
    • 3 - 2 = 1
    • 4 - 3 = 1
    • 6 - 4 = 2
    • Result: 1
function getMinimumDifference_bfs(root):
if root is null:
return 0
values = []
queue = [root]
// Collect all values via BFS
while queue is not empty:
node = queue.pop()
values.append(node.val)
if node.left:
queue.push(node.left)
if node.right:
queue.push(node.right)
// Sort values
sort(values)
// Find min diff between consecutive values
min_diff = infinity
for i in range(1, len(values)):
min_diff = min(min_diff, values[i] - values[i-1])
return min_diff
minimum_absolute_difference_in_bst_bfs.py
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def get_minimum_difference_bfs(root: Optional[TreeNode]) -> int:
"""
BFS level-order traversal to find minimum absolute difference in BST.
Perform in-order traversal using an iterative approach with a stack,
then compute minimum difference between consecutive values.
Time: O(n) - visit each node once
Space: O(h) - queue/stack space, h = height
"""
if not root:
return 0
# Iterative in-order using stack
stack = []
current = root
prev = None
min_diff = float('inf')
while stack or current:
# Go to leftmost node
while current:
stack.append(current)
current = current.left
# Current is None, pop from stack
current = stack.pop()
# Process current node
if prev is not None:
min_diff = min(min_diff, current.val - prev)
prev = current.val
# Visit right subtree
current = current.right
return min_diff
# Test cases
if __name__ == "__main__":
# Example 1: BST with multiple nodes
root1 = TreeNode(4)
root1.left = TreeNode(2)
root1.right = TreeNode(6)
root1.left.left = TreeNode(1)
root1.left.right = TreeNode(3)
print(get_minimum_difference_bfs(root1)) # 1
# Example 2: Single path
root2 = TreeNode(1)
root2.right = TreeNode(5)
root2.right.left = TreeNode(4)
print(get_minimum_difference_bfs(root2)) # 1