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.
- 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
- Queries to add, remove and return the difference of maximum and minimum.
- Sub-tree with minimum color difference in a 2-coloured tree
- Find the node whose xor with x gives minimum value
- Find the node whose sum with X has minimum set bits
- Find a number in minimum steps
- Find the root of the sub-tree whose weighted sum is minimum
- Find the root of the sub-tree whose weighted sum XOR with X is minimum
- Find the weight of the minimum spanning tree
- Find Minimum Depth of a Binary Tree
- Find maximum (or minimum) in 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.