![]() |
VOOZH | about |
Given the root of a Binary Search Tree and two keys, the task is to find the distance between the nodes with the given two keys. Note: The nodes with given keys always exist in the tree.
Approach:
Note: The given approach is optimal only for Binary Search Tree, we have discussed the same problem for simple Binary Tree in Distance between Two Nodes in Binary Tree.
The idea is to start from the root node and check if both the keys are greater than the current node's value, if so, we move to the right child of the current node, else, if both the keys are smaller than the current node's value, we move to the left child of the current node. And for the other case, i.e., one key is smaller and the other key is greater, the current node is Lowest Common Ancestor(LCA), so we find the distance of nodes with given keys from current node and return the sum of distances.
3
Time Complexity: O(h), where h is the height of the Binary Search Tree.
Auxiliary Space: O(h), for recursive stack of size h.