Given two Binary Search Trees(BST), print the elements of both BSTs in sorted form. The expected time complexity is O(m+n) where m is the number of nodes in the first tree and n is the number of nodes in the second tree. The maximum allowed auxiliary space is O(height of the first tree + height of the second tree).
First BST 3 / \ 1 5 Second BST 4 / \ 2 6 Output: 1 2 3 4 5 6 First BST 8 / \ 2 10 / 1 Second BST 5 / 3 / 0 Output: 0 1 2 3 5 8 10
Source: Google interview question
A similar question has been discussed earlier. Let us first discuss the already discussed methods of the previous post which was for Balanced BSTs. Method 1 can be applied here also, but the time complexity will be O(n^2) in the worst case. Method 2 can also be applied here, but the extra space required will be O(n) which violates the constraint given in this question. Method 3 can be applied here but step 3 of method 3 can’t be done in O(n) for an unbalanced BST.
Thanks to Kumar for suggesting the following solution.
The idea is to use iterative inorder traversal. We use two auxiliary stacks for two BSTs. Since we need to print the elements in the sorted form, whenever we get a smaller element from any of the trees, we print it. If the element is greater, then we push it back to stack for the next iteration.
1 2 3 4 5 6
Time Complexity: O(m+n)
Auxiliary Space: O(height of the first tree + height of the second tree)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Merge two BSTs with constant extra space
- Merge Sort with O(1) extra space merge and O(n lg n) time
- Merge two sorted arrays with O(1) extra space
- Merge two sorted arrays in O(1) extra space using QuickSort partition
- Efficiently merging two sorted arrays with O(1) extra space
- Check if two BSTs contain same set of elements
- Check if two given key sequences construct same BSTs
- Generate two BSTs from the given array such that maximum height among them is minimum
- Split a BST into two balanced BSTs based on a value K
- Count pairs from two BSTs whose sum is equal to a given value x
- Nodes from given two BSTs with sum equal to X
- Print all pairs from two BSTs whose sum is greater than the given value
- Connect nodes at same level using constant extra space
- K'th smallest element in BST using O(1) Extra Space
- Find the maximum repeating number in O(n) time and O(1) extra space
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Length of longest palindrome list in a linked list using O(1) extra space
- K'th Largest element in BST using constant extra space
- Create Balanced Binary Tree using its Leaf Nodes without using extra space
- Find duplicates in O(n) time and O(1) extra space | Set 1