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.
- Print all neighbour nodes within distance K
- Print nodes at k distance from root
- Print all nodes at distance k from a given node
- Find distance between two nodes of a Binary Tree
- Queries to find distance between two nodes of a Binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Delete N nodes after M nodes of a linked list
- Sum of all odd nodes in the path connecting two given nodes
- Shortest path in a Binary Maze
- Dijkstra's shortest path algorithm | Greedy Algo-7
- Shortest path to reach one prime to other by changing single digit at a time
- Edit Distance | DP-5
- Check if a given array contains duplicate elements within k distance from each other
- Count number of ways to cover a distance
- Distance of nearest cell having 1 in a binary matrix