Minimum Distance Between BST Nodes
LeetCode 799 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given the root of a Binary Search Tree (BST), return the minimum 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, 100]`.
- `0 <= Node.val <= 10^5`
Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/
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.
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.
Level-order traversal, level-based aggregation, right/left side view.
Solutionsβ
Solution 1: C# (Best: 72 ms)β
| Metric | Value |
|---|---|
| Runtime | 72 ms |
| Memory | 37.2 MB |
| Date | 2021-12-09 |
/**
* 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 MinDiffInBST(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β
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
- 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.