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 i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].
  • Replace the leaf node in trees[i] with trees[j].
  • Remove trees[j] from trees.

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
Input TreesStrategic MergeFinal Result21Tree 1: [2,1]325Tree 2: [3,2,5]54Tree 3: [5,4]1FindRoot2MatchLeaves3BuildTree4ValidBST32514[3,2,5,1,null,4]Key Insight:The root that never appears as a leaf elsewhere must be our final BST rootTutorialsPoint - Merge BSTs to Create Single BST | Strategic Root Finding
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
28.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen