{ "data": { "question": { "questionId": "2060", "questionFrontendId": "1932", "categoryTitle": "Algorithms", "boundTopicId": 863111, "title": "Merge BSTs to Create Single BST", "titleSlug": "merge-bsts-to-create-single-bst", "content": "
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:
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]
.trees[i]
with trees[j]
.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:
\n\nA leaf is a node that has no children.
\n\n\n
Example 1:
\n\n\nInput: trees = [[2,1],[3,2,5],[5,4]]\nOutput: [3,2,5,1,null,4]\nExplanation:\nIn the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].\n\nIn the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].\n\nThe resulting tree, shown above, is a valid BST, so return its root.\n\n
Example 2:
\n\n\nInput: trees = [[5,3,8],[3,2,6]]\nOutput: []\nExplanation:\nPick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].\n\nThe 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.\n\n\n
Example 3:
\n\n\nInput: trees = [[5,4],[3]]\nOutput: []\nExplanation: It is impossible to perform any operations.\n\n\n
\n
Constraints:
\n\nn == trees.length
1 <= n <= 5 * 104
[1, 3]
.trees
have the same value.1 <= TreeNode.val <= 5 * 104
.给你 n
个 二叉搜索树的根节点 ,存储在数组 trees
中(下标从 0 开始),对应 n
棵不同的二叉搜索树。trees
中的每棵二叉搜索树 最多有 3 个节点 ,且不存在值相同的两个根节点。在一步操作中,将会完成下述步骤:
i
和 j
,要求满足在 trees[i]
中的某个 叶节点 的值等于 trees[j]
的 根节点的值 。trees[j]
替换 trees[i]
中的那个叶节点。trees
中移除 trees[j]
。如果在执行 n - 1
次操作后,能形成一棵有效的二叉搜索树,则返回结果二叉树的 根节点 ;如果无法构造一棵有效的二叉搜索树,返回 null
。
二叉搜索树是一种二叉树,且树中每个节点均满足下述属性:
\n\n叶节点是不含子节点的节点。
\n\n\n\n
示例 1:
\n\n\n输入:trees = [[2,1],[3,2,5],[5,4]]\n输出:[3,2,5,1,null,4]\n解释:\n第一步操作中,选出 i=1 和 j=0 ,并将 trees[0] 合并到 trees[1] 中。\n删除 trees[0] ,trees = [[3,2,5,1],[5,4]] 。\n\n在第二步操作中,选出 i=0 和 j=1 ,将 trees[1] 合并到 trees[0] 中。\n删除 trees[1] ,trees = [[3,2,5,1,null,4]] 。\n\n结果树如上图所示,为一棵有效的二叉搜索树,所以返回该树的根节点。\n\n
示例 2:
\n\n\n输入:trees = [[5,3,8],[3,2,6]]\n输出:[]\n解释:\n选出 i=0 和 j=1 ,然后将 trees[1] 合并到 trees[0] 中。\n删除 trees[1] ,trees = [[5,3,8,2,6]] 。\n\n结果树如上图所示。仅能执行一次有效的操作,但结果树不是一棵有效的二叉搜索树,所以返回 null 。\n\n\n
示例 3:
\n\n\n输入:trees = [[5,4],[3]]\n输出:[]\n解释:无法执行任何操作。\n\n\n
\n\n
提示:
\n\nn == trees.length
1 <= n <= 5 * 104
[1, 3]
内。trees
中不存在两棵树根节点值相同的情况。1 <= TreeNode.val <= 5 * 104
.