GeeksforGeeks » Interview Questions
Adobe Interview Question for Software Engineer/Developer about Trees
(4 posts)-
Merge two binary search trees.
-
after a googling, seems flatten out and combine approach is better, just check in stackoverflow
-
@ab, your flatten and combine approach would take worst case MAX(size(Tree1).size(Tree2)) * O(height of Tree) which is roughly quadratic time complexity.
On the other hand , if you don't flatten out the two trees. BST insert takes 0(Height of Tree). So , N * BST Insert takes o(N* HeightOfTree) which also has O(N^^2) complexity in the wost case and O(N*log(N)) in the best scenario. Thank you. -
@freakCoder and @ab, Could you please specify what the desired Order (Space Complexity) is. If one wants to merge two BST trees "IN PLACE", 0(1) space complexity. then we cannot flatten the BST into linked lists, Here is a way to merge 2 BST in place: Thank you.
The best way we could merge the trees in place is something like:
For each node n in first BST {
Go down the 2nd tree and find the appropriate place to insert n
Insert n there
}
Each iteration in the for loop is O(log n) since we are dealing with trees, and the for loop will be iterated n times, so in total we have O(n log n).
link|edit|flag answered Oct 7 '11 at 17:49
Golf Sinteppadon
1592add comment
Reply
You must log in to post.