在 C++ 中查找重复子树
假设我们有一棵二叉树。我们必须找到所有重复的子树。因此,对于每种重复的子树,我们都必须返回其中任何一个的根节点。假设我们有一棵这样的树 −

重复的子树是 −

为解决此问题,我们将按照以下步骤操作 −
- 创建一个数组 ret,绘制一个映射 m
- 定义一个递归方法 solve()。这将以 node 作为输入。它的工作方式如下 −
- 如果 node 为空,则返回 -1
- x := node 的值表示为字符串,然后在后面连接 “#” 。
- left := node 的左侧解决,right := node 的右侧解决
- x :=x 连接 “#” 连接 left,连接 “#” 连接 right
- m[x] 增加 1
- 如果 m[x] 为 2,则将 node 插入到 ret 中
- 返回 x
- 从主方法调用 solve(root) 并返回 ret
让我们看看以下实现,以更好地理解 −
示例
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
} else {
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
} else {
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
} else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr->val == 0 || curr == NULL){
cout << "null" << ", ";
} else {
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
vector <TreeNode*> ret;
map <string, int> m;
string solve(TreeNode* node){
if(!node || node->val == 0){
return "-1";
}
string x = to_string(node->val);
x += "#";
string left = solve(node->left);
string right = solve(node->right);
x = x + "#" + left + "#" + right;
m[x]++;
if(m[x] == 2){
ret.push_back(node);
}
return x;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
ret.clear();
m.clear();
solve(root);
return ret;
}
};
main(){
vector<int> v = {1,2,3,4,NULL,2,4,NULL,NULL,NULL,NULL,4};
Solution ob;
TreeNode *root = make_tree(v);
vector<TreeNode*> trees = ob.findDuplicateSubtrees(root);
for(TreeNode *t : trees){
tree_level_trav(t);
}
}输入
[1,2,3,4,null,2,4,null,null,null,null,4]
输出
[4, ] [2, 4, ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP