Merge BSTs to Create Single BST Problem
Description
LeetCode Problem 1932.
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.
Example 1:

Input: trees = [[2,1],[3,2,5],[5,4]]
Output: [3,2,5,1,null,4]
Explanation:
In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].
Delete trees[0], so trees = [[3,2,5,1],[5,4]].

In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].
Delete trees[1], so trees = [[3,2,5,1,null,4]].

The resulting tree, shown above, is a valid BST, so return its root.
Example 2:

Input: trees = [[5,3,8],[3,2,6]]
Output: []
Explanation:
Pick i=0 and j=1 and merge trees[1] into trees[0].
Delete trees[1], so trees = [[5,3,8,2,6]].

The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.
Example 3:

Input: trees = [[5,4],[3]]
Output: []
Explanation: It is impossible to perform any operations.
Constraints:
n == trees.length1 <= 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
treeshave the same value. - All the trees in the input are valid BSTs.
1 <= TreeNode.val <= 5 * 10^4.
Solution
Approach: Find the Root, Merge While Traversing
Each tree has at most 3 nodes, and a merge only replaces a leaf by another tree whose root has the same value.
- Map every root value to its tree and collect the values of all leaves.
- The final root is a tree whose root value is not the value of any leaf, since nothing can be hung below it. If there is not exactly one such tree, return
null(two of them can never be joined; none means the trees form a cycle). - Walk down from that root with an allowed open range
(lo, hi). A node whose value is outside the range breaks the BST property, so returnnull. When a leaf's value is the root of an unused tree, graft that tree's children onto the leaf (and mark the tree as used) before going on to its children, narrowing the range to(lo, val)for the left child and(val, hi)for the right child. - At the end, exactly
n - 1trees must have been merged. Otherwise some trees were never reachable from the root (for instance, a cycle among them), so returnnull.
The merged tree is valid when the traversal never leaves its allowed range.
Complexity: O(n) time and O(n) space, where n is the number of trees (the number of nodes is at most 3n).
class Solution:
def canMerge(self, trees: List[TreeNode]) -> Optional[TreeNode]:
roots = {t.val: t for t in trees}
leaves = set()
for t in trees:
for c in (t.left, t.right):
if c:
leaves.add(c.val)
tops = [t for t in trees if t.val not in leaves]
if len(tops) != 1:
return None
root = tops[0]
merged = 0
def dfs(node, lo, hi):
nonlocal merged
if node is None:
return True
if not lo < node.val < hi:
return False
if node.left is None and node.right is None and node.val in roots and roots[node.val] is not node:
t = roots.pop(node.val)
node.left, node.right = t.left, t.right
merged += 1
return dfs(node.left, lo, node.val) and dfs(node.right, node.val, hi)
ok = dfs(root, 0, 10**9)
return root if ok and merged == len(trees) - 1 else None