Given a Binary Search Tree and two keys in it. Find the distance between two nodes with given two keys. It may be assumed that both keys exist in BST.
Input: Root of above tree a = 3, b = 9 Output: 4 Distance between 3 and 9 in above BST is 4. Input: Root of above tree a = 9, b = 25 Output: 3 Distance between 9 and 25 in above BST is 3.
We have discussed distance between two nodes in binary tree. The time complexity of this solution is O(n)
In the case of BST, we can find the distance faster. We start from the root and for every node, we do following.
- If both keys are greater than the current node, we move to the right child of the current node.
- If both keys are smaller than current node, we move to left child of current node.
- If one keys is smaller and other key is greater, current node is Lowest Common Ancestor (LCA) of two nodes. We find distances of current node from two keys and return sum of the distances.
Time Complexity : O(h) where h is height of Binary Search Tree.
This article is contributed by Shweta Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Maximum element between two nodes of BST
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Find k-th smallest element in BST (Order Statistics in BST)
- Find distance between two nodes of a Binary Tree
- Queries to find distance between two nodes of a Binary tree
- Find distance between two nodes in the given Binary tree for Q queries
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Count BST nodes that lie in a given range
- Sum of cousin nodes of a given node in a BST
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Sum of all odd nodes in the path connecting two given nodes
- Print nodes at k distance from root
- Print all nodes at distance k from a given node
- Print all neighbour nodes within distance K
- Print all nodes at distance K from given node: Iterative Approach
- Count of all prime weight nodes between given nodes in the given Tree
- Split a BST into two balanced BSTs based on a value K