当前位置:网站首页>Merge multiple binary search trees
Merge multiple binary search trees
2022-06-11 19:09:00 【AlbertOS】
introduce
Here you are. n individual The root node of binary search tree , Stored in array trees in ( Subscript from 0 Start ), Corresponding n A different binary search tree .trees Every binary search tree in At most 3 Nodes , And there are no two root nodes with the same value . In one step , The following steps will be completed :
- Select two Different Subscript i and j , Requirements met in trees[i] One of the Leaf nodes The value is equal to the trees[j] Of Value of root node .
- use trees[j] Replace trees[i] The leaf node in .
- from trees Remove trees[j] .
If in execution n - 1 After the first operation , Can form an effective binary search tree , Returns the result of the binary tree The root node ; If we can't construct an effective binary search tree , return null .
Binary search tree is a kind of binary tree , And each node in the tree satisfies the following attributes :
- The values in the left subtree of any node are Strictly less than The value of this node .
- The values in the right subtree of any node are Strictly greater than The value of this node .
Leaf nodes are nodes that do not contain child nodes .
Example 1( Success )

Input :trees = [[2,1],[3,2,5],[5,4]]
Output :[3,2,5,1,null,4]
explain :
In the first step , elect i=1 and j=0 , And will trees[0] Merge into trees[1] in .
Delete trees[0] ,trees = [[3,2,5,1],[5,4]] .
In the second step , elect i=0 and j=1 , take trees[1] Merge into trees[0] in .
Delete trees[1] ,trees = [[3,2,5,1,null,4]] .
The result tree is shown in the figure above , For an efficient binary search tree , So return to the root node of the tree .
Example 2( Can't be )

Input :trees = [[5,3,8],[3,2,6]]
Output :[]
explain :
elect i=0 and j=1 , And then trees[1] Merge into trees[0] in .
Delete trees[1] ,trees = [[5,3,8,2,6]] .
The result tree is shown in the figure above . Only one valid operation can be performed , But the result tree is not an effective binary search tree , So back null .
Example 3

Input :trees = [[5,4],[3]]
Output :[]
explain : Unable to perform any operation .
Tips
- n == trees.length
- 1 <= n <= 5 * 104
- The number of nodes in each tree is in the range [1, 3] Inside .
- Each node of input data may have child nodes, but there are no child nodes of child nodes
- trees There is no case in which the root node values of two trees are the same .
- All the trees in the input are Effective binary tree search tree .
- 1 <= TreeNode.val <= 5 * 104
For a given second i i i tree tree [ i ] \textit{tree}[i] tree[i], Note that the value of its root node is root [ i ] \textit{root}[i] root[i]. We need to find another tree , It's No j ( j ≠ i ) j~(j \neq i) j (j=i) Tree . The first jj A tree must have a value of root [ i ] \textit{root}[i] root[i] Leaf node of , So we can put the i i i A tree and the first j j j Tree merging .
If there is no section that meets the requirements j j j tree , So the first i i i The root node of a tree must be the root node of the merged tree . obviously , Such a second i i i A tree must have exactly one and only one .
If there is a unique j j j tree , Then we have to put the i i i A tree and j j j Tree merging . If you don't do that , At least two values in the merged tree are root [ i ] \textit{root}[i] root[i] The node of , It must not be a binary search tree .
If there are multiple viable trees j j j tree , So which tree should we choose ? We found that , Because the title guarantees that there are no two root nodes with the same value , So, among the trees we didn't choose , Their values are root [ i ] \textit{root}[i] root[i] All leaf nodes will be preserved , And we chose the first j j j A tree and the first i i i When the trees merge , A value of root [ i ] \textit{root}[i] root[i] The node of . In this way, there are at least two values in the merged tree root [ i ] \textit{root}[i] root[i] The node of , It must not be a binary search tree .
therefore , If the root node of a tree needs to be merged , Then the merging scheme is the only one .
solution
We first use a hash set of the values of each leaf node leaves \textit{leaves} leaves Store it , Then you can find the root node of the merged tree . Remember that the tree containing the root node is tree [ pivot ] \textit{tree}[\textit{pivot}] tree[pivot], be root [ pivot ] \textit{root}[\textit{pivot}] root[pivot] Can't be in leaves \textit{leaves} leaves There has been .( The title says that there is no root node with the same value , So use hash Will be faster )
If there is no... That meets the requirements tree [ pivot ] \textit{tree}[\textit{pivot}] tree[pivot], Then it is impossible to construct a binary search tree ; If the requirements are met tree [ pivot ] \textit{tree}[\textit{pivot}] tree[pivot] Is not the only , Then we can choose one at random ( If the tree that meets the requirements is not unique, it is impossible to construct a binary search tree , This uniqueness is mentioned in the prompt ).We know , A binary tree is a binary search tree , If and only if its middle order ergodic sequence is strictly monotonically increasing . therefore , We from tree [ pivot ] \textit{tree}[\textit{pivot}] tree[pivot] The root node of , Use the recursive method to perform a special middle order traversal :
- When we traverse to a non leaf node , We follow the conventional method of middle order traversal , Continue traversal ;
- When we traverse to a leaf node , This leaf node may be merged with the root node of another tree . Let the value of this leaf node be xx, If there is a root node, the value is also xx The tree of , We will merge it with the leaf node . After the merger , The leaf node may become a non leaf node , We need to continue to follow the normal middle order traversal method , Continue traversal .
In the process of traversal , If we find that the value traversed is not strictly monotonically increasing , Description cannot construct a binary search tree . meanwhile , If the traversal ends , However, the root node of a certain tree has not been traversed , That also means that we can't construct a binary search tree .
Code :
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
TreeNode* canMerge(vector<TreeNode*>& trees) {
// A hash set that stores all leaf node values
unordered_set<int> leaves;
// Storage ( Root node value , Trees ) Hash mapping of key value pairs
unordered_map<int, TreeNode*> candidates;
for (TreeNode* tree: trees) {
if (tree->left) {
leaves.insert(tree->left->val);
}
if (tree->right) {
leaves.insert(tree->right->val);
}
candidates[tree->val] = tree;
}
// The stored sequence traverses the last traversed value , It is convenient to check the strict monotonicity
int prev = 0;
// In the sequence traversal , The return value indicates whether there is strict monotonicity
function<bool(TreeNode*)> dfs = [&](TreeNode* tree) {
if (!tree) {
return true;
}
// If you traverse to the leaf node , And there are trees that can be merged , Then merge
if (!tree->left && !tree->right && candidates.count(tree->val)) {
tree->left = candidates[tree->val]->left;
tree->right = candidates[tree->val]->right;
// After the merger , Remove the tree from the hash map , In order to judge whether all trees have been traversed after traversal
candidates.erase(tree->val);
}
// First traverse the left subtree
if (!dfs(tree->left)) {
return false;
}
// Then traverse the current node
if (tree->val <= prev) {
return false;
};
prev = tree->val;
// Finally, traverse the right subtree
return dfs(tree->right);
};
for (TreeNode* tree: trees) {
// Find the root node of the merged tree
if (!leaves.count(tree->val)) {
// Remove it from the hash map
candidates.erase(tree->val);
// Start traversing from the root node
// If the middle order ergodic is strictly monotonic , And the root nodes of all trees are traversed to , It shows that the binary search tree can be constructed
return (dfs(tree) && candidates.empty()) ? tree : nullptr;
}
}
return nullptr;
}
};
边栏推荐
- MOS transistor 24n50 parameters of asemi, 24n50 package, 24n50 size
- Use canvas to add text watermark to the page
- leetcode:66. add one-tenth
- On high availability architecture
- 关于富文本储存数据库格式转译问题
- cf:F. Shifting String【字符串按指定顺序重排 + 分组成环(切割联通分量) + 各组最小相同移动周期 + 最小公倍数】
- 手把手教你学会FIRST集和FOLLOW集!!!!吐血收藏!!保姆级讲解!!!
- Kubernetes binary installation (v1.20.15) (VIII) deploying network plug-ins
- Startup process of datanode
- 司空见惯 - 会议室名称
猜你喜欢

记录一下phpstudy配置php8.0和php8.1扩展redis
Function development of user information management

Key contents that wwdc22 developers need to pay attention to
![[image denoising] image denoising based on Markov random field with matlab code](/img/ef/d28b89a47723b43705fca07261c958.png)
[image denoising] image denoising based on Markov random field with matlab code

Flash ckeditor rich text compiler can upload and echo images of articles and solve the problem of path errors

highcharts设置柱状图宽度、渐变、圆角、柱子上方数据

Gmail: how do I recall an outgoing message?

【视频去噪】基于SALT实现视频去噪附Matlab代码

视觉SLAM十四讲笔记-10-2

Today's sleep quality record is 60 points
随机推荐
Uploading and downloading of necessary files in development
Experience of remote office communication under epidemic situation | community essay solicitation
美国通胀率8.6%创41年历史新高!通胀高烧不退?股票、加密市场先跌为敬!
7-3 组合问题(*)
用户信息管理的功能开发
leetcode:926. 将字符串翻转到单调递增【前缀和 + 模拟分析】
KMP! You deserve it!!! Run directly!
The US inflation rate reached a 41 year high of 8.6%! High inflation fever? The stock and encryption markets fell first!
MOS transistor 24n50 parameters of asemi, 24n50 package, 24n50 size
构造敌方坦克
视觉SLAM十四讲笔记-10-2
On Workflow selection
【信号去噪】基于FFT和FIR实现信号去噪附matlab代码
Do you know that public fields are automatically filled in
5g communication test manual based on Ti am5728 + artix-7 FPGA development board (dsp+arm)
Overall process of software development
Practice of Flink CDC in Dajian cloud warehouse
Crop disease detection using image processing technology and convolutional neural network (CNN)
《经济学人》:WTO MC12重启 数字经济成为全球经济复苏和增长的核心引擎
SQL injection vulnerability learning 1: phpstudy integrated environment building DVWA shooting range


