Question
Download Solution PDFTwo balanced binary trees are given with m and n elements, respectively. They can be merged into a balanced binary search tree in ______ time.
- O(m*n)
- O(m + n)
- O(m*log n)
- O(m*log(m + n))
Answer (Detailed Solution Below)
Option 2 : O(m + n)
India's Super Teachers for all govt. exams Under One Roof
FREE
Demo Classes Available*
Enroll For Free Now
Detailed Solution
Download Solution PDFThe correct answer is: Option 2) O(m + n)
Key Points
Given: Two balanced Binary Search Trees (BSTs), one with m
nodes and the other with n
nodes.
Objective: Merge them into a new balanced Binary Search Tree.
Approach:
- Step 1: Perform
in-order traversal
of both BSTs.
This will give two sorted arrays of sizem
andn
, respectively.
Time complexity for in-order traversal of both trees =O(m + n)
- Step 2: Merge the two sorted arrays.
This is similar to merging in merge sort.
Time complexity =O(m + n)
- Step 3: Construct a balanced BST from the merged sorted array.
This can be done using a divide-and-conquer approach (similar to building BST from sorted array).
Time complexity =O(m + n)
Total Time Complexity: O(m + n) + O(m + n) + O(m + n) = O(m + n)
Conclusion:
Merging two balanced BSTs into one balanced BST can be done in linear time with respect to the total number of nodes.
✅ Final Answer: Option 2) O(m + n)
India’s #1 Learning Platform
Start Complete Exam Preparation
Daily Live MasterClasses
Practice Question Bank
Mock Tests & Quizzes
Trusted by 7.3 Crore+ Students