1932. Merge BSTs to Create Single BST
https://leetcode.com/problems/merge-bsts-to-create-single-bst
Description
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, ornull 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:

Example 2:

Example 3:

Example 4:

Constraints:
n == trees.length1 <= n <= 5 * 104The 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 * 104.
ac
Last updated
Was this helpful?