1932. Merge BSTs to Create Single BST LeetCode Solution
In this guide, you will get 1932. Merge BSTs to Create Single BST LeetCode Solution with the best time and space complexity. The solution to Merge BSTs to Create Single BST problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Merge BSTs to Create Single BST solution in C++
- Merge BSTs to Create Single BST solution in Java
- Merge BSTs to Create Single BST solution in Python
- Additional Resources
Problem Statement of Merge BSTs to Create Single BST
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.
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.length
1 <= n <= 5 * 104
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 trees have the same value.
All the trees in the input are valid BSTs.
1 <= TreeNode.val <= 5 * 104.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
1932. Merge BSTs to Create Single BST LeetCode Solution in C++
class Solution {
public:
TreeNode* canMerge(vector<TreeNode*>& trees) {
unordered_map<int, TreeNode*> valToNode; // {val: node}
unordered_map<int, int> count; // {val: freq}
for (TreeNode* tree : trees) {
valToNode[tree->val] = tree;
++count[tree->val];
if (tree->left)
++count[tree->left->val];
if (tree->right)
++count[tree->right->val];
}
for (TreeNode* tree : trees)
if (count[tree->val] == 1) {
if (isValidBST(tree, nullptr, nullptr, valToNode) &&
valToNode.size() <= 1)
return tree;
return nullptr;
}
return nullptr;
}
private:
bool isValidBST(TreeNode* tree, TreeNode* minNode, TreeNode* maxNode,
unordered_map<int, TreeNode*>& valToNode) {
if (tree == nullptr)
return true;
if (minNode && tree->val <= minNode->val)
return false;
if (maxNode && tree->val >= maxNode->val)
return false;
if (!tree->left && !tree->right && valToNode.contains(tree->val)) {
const int val = tree->val;
tree->left = valToNode[val]->left;
tree->right = valToNode[val]->right;
valToNode.erase(val);
}
return isValidBST(tree->left, minNode, tree, valToNode) &&
isValidBST(tree->right, tree, maxNode, valToNode);
}
};
/* code provided by PROGIEZ */
1932. Merge BSTs to Create Single BST LeetCode Solution in Java
class Solution {
public TreeNode canMerge(List<TreeNode> trees) {
Map<Integer, TreeNode> valToNode = new HashMap<>(); // {val: node}
Map<Integer, Integer> count = new HashMap<>(); // {val: freq}
for (TreeNode tree : trees) {
valToNode.put(tree.val, tree);
count.merge(tree.val, 1, Integer::sum);
if (tree.left != null)
count.merge(tree.left.val, 1, Integer::sum);
if (tree.right != null)
count.merge(tree.right.val, 1, Integer::sum);
}
for (TreeNode tree : trees)
if (count.get(tree.val) == 1) {
if (isValidBST(tree, null, null, valToNode) && valToNode.size() <= 1)
return tree;
return null;
}
return null;
}
private boolean isValidBST(TreeNode tree, TreeNode minNode, TreeNode maxNode,
Map<Integer, TreeNode> valToNode) {
if (tree == null)
return true;
if (minNode != null && tree.val <= minNode.val)
return false;
if (maxNode != null && tree.val >= maxNode.val)
return false;
if (tree.left == null && tree.right == null && valToNode.containsKey(tree.val)) {
final int val = tree.val;
tree.left = valToNode.get(val).left;
tree.right = valToNode.get(val).right;
valToNode.remove(val);
}
return //
isValidBST(tree.left, minNode, tree, valToNode) && //
isValidBST(tree.right, tree, maxNode, valToNode);
}
}
// code provided by PROGIEZ
1932. Merge BSTs to Create Single BST LeetCode Solution in Python
class Solution:
def canMerge(self, trees: list[TreeNode]) -> TreeNode | None:
valToNode = {} # {val: node}
count = collections.Counter() # {val: freq}
for tree in trees:
valToNode[tree.val] = tree
count[tree.val] += 1
if tree.left:
count[tree.left.val] += 1
if tree.right:
count[tree.right.val] += 1
def isValidBST(tree: TreeNode | None, minNode: TreeNode | None,
maxNode: TreeNode | None) -> bool:
if not tree:
return True
if minNode and tree.val <= minNode.val:
return False
if maxNode and tree.val >= maxNode.val:
return False
if not tree.left and not tree.right and tree.val in valToNode:
val = tree.val
tree.left = valToNode[val].left
tree.right = valToNode[val].right
del valToNode[val]
return isValidBST(
tree.left, minNode, tree) and isValidBST(
tree.right, tree, maxNode)
for tree in trees:
if count[tree.val] == 1:
if isValidBST(tree, None, None) and len(valToNode) <= 1:
return tree
return None
return None
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.