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.
- Print nodes at k distance from root
- Print all nodes at distance k from a given node
- Print all neighbour nodes within distance K
- Find distance between two nodes of a Binary Tree
- Print all nodes at distance K from given node: Iterative Approach
- Find distance between two nodes in the given Binary tree for Q queries
- 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
- Count of all prime weight nodes between given nodes in the given Tree
- 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
- Distance of nearest cell having 1 in a binary matrix
- Count number of ways to cover a distance
- Check if a given array contains duplicate elements within k distance from each other
- Minimum Manhattan distance covered by visiting every coordinates from a source to a final vertex
- Count BST nodes that lie in a given range