You are given a Binary Search Tree containing integers. How would you in linear time find the least difference between the values of any two node in the BST.
Here is the algorithm
In order traversal of a BST traverses it in sorted order. So, for every node, we will find its difference from the previous node in the in-order traversal of the tree. If this difference is smaller than the previous minimum difference, we will update the previous minimum difference. Following are the steps to follow:
Here is the pseudocode:
function inorder(Node curr) {
if (curr is null)
return;
inorder(curr.left);
if (prev is not null)
ans = Math.min(curr.data - prev.data, ans);
prev = curr;
inorder(curr.right);
}
function minDiff(BST root) {
prev = NULL;
ans = INT_MAX;
inorder(root, prev, ans);
return ans;
}
Get Answers For Free
Most questions answered within 1 hours.