#1932
Merge BSTs to Create Single BST
HardArrayHash TableTreeDepth-First SearchBinary Search TreeBinary TreeHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all pairs, we can build a single tree by maintaining a set of values and merging directly when possible. This reduces unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Create a set to store all values from the trees.
- 2Step 2: For each tree, check if its leaves can be merged with the root of another tree using the set.
- 3Step 3: If a merge is possible, perform it and update the set accordingly.
- 4Step 4: Continue until only one tree remains or no more merges can be performed.
solution.py31 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def merge_trees(trees):
9 values = set()
10 for tree in trees:
11 collect_values(tree, values)
12 while len(trees) > 1:
13 merged = False
14 for i in range(len(trees)):
15 for j in range(len(trees)):
16 if i != j and trees[j].val in values:
17 trees[i] = merge(trees[i], trees[j])
18 trees.pop(j)
19 merged = True
20 break
21 if merged:
22 break
23 return trees[0] if trees else None
24
25def collect_values(node, values):
26 if node:
27 values.add(node.val)
28 collect_values(node.left, values)
29 collect_values(node.right, values)
30
31# Helper functions can_merge and merge would be defined here.ℹ
Complexity note: The time complexity is O(n) because we only traverse each tree once to collect values and then merge efficiently based on those values.
- 1Merging requires careful value checking to maintain BST properties.
- 2Understanding tree structures is crucial for efficient merging.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.