In the following, B1 and B2 are two binary search trees such that every key in B
ID: 3666767 • Letter: I
Question
In the following, B1 and B2 are two binary search trees such that every key in B1 is smaller than every key in B2. Describe an algorithm that, given pointers b1 and b2 to the roots of B1 and B2, merges B1 and B2 into a single binary search tree T. Your algorithm should satisfy the following two properties:
1. Its worst{case running time is O(min{h1,h2}), where h1 and h2 are the heights of B1 and B2.
2. The height of the merged tree T is at most max{h1,h2}+ 1. Note that the heights h1 and h2 are not given to the algorithm (in other words, the algorithm does not know" the heights of B1 and B2). Note also that B1, B2 and T are not required to be balanced. Describe your algorithm, and justify its correctness and worst-case running time, in clear and concise English.
Explanation / Answer
The simple algorthim for merging the two BST's into a single tree..see the below simple english algorithm..
Flattening a BST into a sorted list is O(N)
It's just "in-order" iteration on the whole tree.
Doing it for both is O(n1+n2)
Merging two sorted lists is into one sorted list is O(n1+n2).
Keep pointers to the heads of both lists
Pick the smaller head and advance its pointer
This is how the merge of merge-sort works
Creating a perfectly balanced BST from a sorted list is O(N)
The value at the middle would be the root, and recurse.
In our case the sorted list is of size n1+n2. so O(n1+n2)
The resulting tree would be the conceptual BST of binary searching the list
Three steps of O(n1+n2) result in O(n1+n2)
For n1 and n2 of the same order of magnitude, that's better than O(n1 * log(n2))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.