Dsa
Trees
Medium
K Smallest Elements from Two BSTs
You are given two binary search trees (BSTs) and an integer k. Your task is to find the k smallest elements from the union of these two BSTs.
Input format:
The first line contains the integer k (1 <= k <= 1000). The next line begins with an integer n (1 <= n <= 1000), the number of nodes in the first BST, followed by n lines each containing the node value and its left and right children. Then, a line with an integer m (1 <= m <= 1000) follows for the second BST, followed by m lines similar to the first BST.
Output format:
Print k smallest elements as a space-separated string.
Example:
Input:
3
3
4 2 5
2 1 -1
5 -1 -1
3
1 -1 -1
6 -1 -1
Output:
1 2 4
Key concepts
treesbstk smallest
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now