Skip to content

Practice Merge BSTs to Create Single BST

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#1932
LeetCode Problem

Merge BSTs to Create Single BST

Problem Statement

Each input BST has at most three nodes and a distinct root value. An operation replaces a leaf of one tree with another entire tree whose root has that same value, then removes the grafted tree from the input collection. After exactly trees.length - 1 operations, return the root if one valid BST can remain, otherwise null. For each node, every value in its left subtree must be strictly smaller than that node value, and every value in its right subtree strictly larger.

Source: Merge BSTs to Create Single BST on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
trees = [[2,1],[3,2,5],[5,4]]
Output
[3,2,5,1,null,4]

# Example 2

Input
trees = [[5,3,8],[3,2,6]]
Output
[]

# Example 3

Input
trees = [[5,4],[3]]
Output
[]

Constraints

n == trees.length
1 <= n <= 5 * 10^4
The number of nodes in each tree is in the range [1, 3].
Each node in the input may have children but no grandchildren.
No two roots of trees have the same value.
All the trees in the input are valid BSTs.
1 <= TreeNode.val <= 5 * 10^4.

Related LeetCode Problems

Practice more problems similar to Merge BSTs to Create Single BST.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.