🧠 Approach: Inorder Traversal (Sorted View of BST)
In a BST, an inorder traversal gives us a sorted sequence of values.
So instead of comparing every pair of nodes (which would be O(n²)), we can:
- Do an inorder traversal.
- At each step, compare the current node’s value with the previous node’s value.
- Keep track of the minimum absolute difference.
Why this works:
In a sorted list, the smallest difference must be between two consecutive values.
✅ Code (JavaScript):
var getMinimumDifference = function (root) {
let prev = null;
let minimum = Infinity;
function inorder(node) {
if (!node) return;
inorder(node.left);
if (prev !== null) {
minimum = Math.min(minimum, Math.abs(node.val - prev.val));
}
prev = node;
inorder(node.right);
}
inorder(root);
return minimum;
};
📦 Example:
For a tree like:
4
/ \
2 6
/ \
1 3
Inorder traversal: [1, 2, 3, 4, 6]
Minimum difference = min(1, 1, 1, 2) = 1
⏱ Time & Space Complexity
Type | Complexity |
---|---|
Time | O(n) — Every node visited once |
Space | O(h) — Due to recursion stack (h = height of tree) |
Top comments (0)