Ctrl K

Merge Two Search Trees

Medium
You are given the roots of two binary search trees, first and second. In each tree, every value in a node's left subtree is no greater than the node's value, and every value in its right subtree is no smaller. Return a single list with the values of all nodes from both trees in non-decreasing order. A value held by several nodes appears in the answer that many times. Either tree may be empty. Try to avoid a full sort and use the fact that both trees are already ordered.
Example 1
first=tree_node([6, 2, 9]), second=tree_node([4, 1, 7]) → [1, 2, 4, 6, 7, 9]

The first tree holds 2, 6, 9 and the second holds 1, 4, 7. Together in ascending order: 1, 2, 4, 6, 7, 9.

Example 2
first=tree_node([3, None, 5]), second=tree_node([5, 3]) → [3, 3, 5, 5]

Duplicates stay: each value appears as many times as there are nodes holding it.

Example 3
first=tree_node([]), second=tree_node([-8]) → [-8]

The first tree is empty, so the answer is just the second tree.

Constraints
  • 0 ≤ number of nodes in each tree ≤ 5000
  • -10⁵ ≤ Node.val ≤ 10⁵
  • Both trees are valid search trees
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumK-th Smallest in a Search Tree MediumTree Columns, Top Down MediumBiggest Search Subtree Medium
loading Python…
Input
first=tree_node([6, 2, 9]), second=tree_node([4, 1, 7])
Expected
[1, 2, 4, 6, 7, 9]

Run checks the first 3 tests in your browser. Submit checks all 51 tests on the server, hidden ones included.