22(July) Merge two BST 's
23. Merge Two BSTs
The problem can be found at the following link: Question Link
Problem Description
Given two BSTs, return elements of merged BSTs in sorted form.
Examples:
Input:
BST1:
5
/ \
3 6
/ \
2 4
BST2:
2
/ \
1 3
\
7
/
6Output:
Explanation: After merging and sorting the two BSTs, we get 1 2 2 3 3 4 5 6 6 7.
My Approach
Inorder Traversal:
Create a function
inorderto perform an inorder traversal on a BST and store the elements in a vector (C++) or list (Java and Python).
Merge BSTs:
Create a function
mergeto merge two BSTs. Perform an inorder traversal on both BSTs to get the elements.Sort the combined list of elements.
Return:
Return the sorted list of elements.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(m + n), as we perform an inorder traversal of both BSTs and sort the combined list.
Expected Auxiliary Space Complexity: O(Height of BST1 + Height of BST2 + m + n), as we use additional space for the inorder traversal stack and the combined list of elements.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated