Given 2 Binary Search Trees, select one node from each tree such that their absolute difference is minimum possible. Assume each BST has at-least one node.
Input : N1 = 7, N2 = 2 BST1 : 5 / \ 3 7 / \ / \ 2 4 6 8 BST2 : 11 \ 13 Output : 3 8 is largest number in the first BST and 11 is smallest in the second. Thus, the final answer will be 11-8 = 3 Input : N1 = 4, N2 = 2 BST1 : 3 / \ 2 4 \ 14 BST2 : 7 \ 13 Output : 1
The idea is to use the two-pointer technique and iterating the pointers using the following steps.
- Create forward iterators for both the BST’s. Let’s say that the value of nodes they are pointing at are v1 and v2 respectively.
- Now at each step:
- Update final ans as min(ans, abs(v1-v2)) .
- If v1 < v2, move iterator of first BST else move the iterator of the second BST.
- Repeat above steps till both the BST’s are pointing to a valid nodes.
Time complexity: O(N1 + N2) where N1 and N2 are the bumber of nodes of first and second BST respectively.
Space Complexity: O(H1 + H2) where H1 and H2 are the heights of first and second BST respectively.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find the node whose absolute difference with X gives minimum value
- Pair with minimum absolute difference | BST
- Pair with minimum absolute difference after solving each query
- Find the node whose absolute difference with X gives maximum value
- Sort an array according to absolute difference with given value using Functors
- Longest subsequence such that absolute difference between every pair is atmost 1
- Queries to add, remove and return the difference of maximum and minimum.
- Find the node whose xor with x gives minimum value
- Sub-tree with minimum color difference in a 2-coloured tree
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Find the node whose sum with X has minimum set bits
- Find a number in minimum steps
- Find minimum y coordinates from set of N lines in a plane
- Find maximum (or minimum) in Binary Tree
- Find the minimum dominating set of a Binary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.