Merge BSTs to Create Single BST - Problem
You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value.
In one operation, you can:
- Select two distinct indices
iandjsuch that the value stored at one of the leaves oftrees[i]is equal to the root value oftrees[j]. - Replace the leaf node in
trees[i]withtrees[j]. - Remove
trees[j]fromtrees.
Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.
A BST (binary search tree) is a binary tree where each node satisfies the following property:
- Every node in the node's left subtree has a value strictly less than the node's value.
- Every node in the node's right subtree has a value strictly greater than the node's value.
A leaf is a node that has no children.
Input & Output
Example 1 — Multiple Small BSTs
$
Input:
trees = [[2,1],[3,2,5],[5,4]]
›
Output:
[3,2,5,1,null,4]
💡 Note:
Tree with root 3 has leaves [2,5]. We can merge tree with root 2 into leaf 2, and tree with root 5 into leaf 5, creating a valid BST.
Example 2 — No Valid Merge
$
Input:
trees = [[5,3,8],[3,2,6]]
›
Output:
null
💡 Note:
Cannot create a valid BST because no valid merging strategy exists that maintains BST properties.
Example 3 — Single Tree
$
Input:
trees = [[1,null,3]]
›
Output:
[1,null,3]
💡 Note:
Only one tree provided, so return it as is since it's already a valid BST.
Constraints
- n == trees.length
- 1 ≤ n ≤ 5×104
- Each tree in the input is a BST with at most 3 nodes
- No two roots have the same value
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code