Skip to main content

Minimum Absolute Difference in BST

LeetCode 530 | Difficulty: Easy​

Easy

Problem Description​

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.

Example 1:

Input: root = [4,2,6,1,3]
Output: 1

Example 2:

Input: root = [1,0,48,null,null,12,49]
Output: 1

Constraints:

- The number of nodes in the tree is in the range `[2, 10^4]`.

- `0 <= Node.val <= 10^5`

Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

Topics: Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree


Approach​

Tree DFS​

Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β†’ go right β†’ combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.

When to use

Path problems, subtree properties, tree structure manipulation.

Tree BFS (Level-Order)​

Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.

When to use

Level-order traversal, level-based aggregation, right/left side view.


Solutions​

Solution 1: C# (Best: 96 ms)​

MetricValue
Runtime96 ms
Memory41.1 MB
Date2021-12-09
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int GetMinimumDifference(TreeNode root) {
int min = Int32.MaxValue;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root, pre = null;
while (cur != null || stack.Count != 0)
{
if (cur != null)
{
stack.Push(cur);
cur = cur.left;
}
else
{
cur = stack.Pop();
if (pre != null)
min = Math.Min(min, cur.val - pre.val);
pre = cur;
cur = cur.right;
}
}
return min;
}
}

Complexity Analysis​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Consider: "What information do I need from each subtree?" β€” this defines your recursive return value.