Sponsored
Sponsored
An inorder traversal of a BST yields nodes in non-decreasing order. By performing an inorder traversal, we can collect the values of the nodes in a sorted manner and then iterate through these values to find the minimum difference between successive nodes.
Time Complexity: O(N), where N is the number of nodes in the tree since we visit each node exactly once.
Space Complexity: O(H) due to the recursion stack, where H is the height of the tree.
1var minDiffInBST = function(root) {
2 let minDiff = Infinity;
3 let prev = null;
4
5 const inorder = (node) => {
6 if (!node) return;
7 inorder(node.left);
8 if (prev !== null) {
9 minDiff = Math.min(minDiff, node.val - prev);
10 }
11 prev = node.val;
12 inorder(node.right);
13 };
14
15 inorder(root);
16 return minDiff;
17};
This JavaScript implementation recursively traverses the tree in inorder fashion while computing the minimum difference between consecutive node values by maintaining a running prev
state.
The Morris Traversal is an inorder tree traversal technique that uses constant space by reusing the tree structure. It involves temporarily rearranging the tree to allow traversal without explicit stack use.
Time Complexity: O(N) where each edge is traversed at most twice, once down and once up.
Space Complexity: O(1) because it does not use stack or recursion.
1
Python implementation applies Morris Traversal for an efficient in-order walk, using tree pointers for thread simulation rather than auxiliary space.