이진 트리가 있다고 가정합니다. 모든 중복 하위 트리를 찾아야 합니다. 따라서 각 종류의 중복 하위 트리에 대해 그 중 하나의 루트 노드를 반환해야 합니다. 따라서 다음과 같은 트리가 있다고 가정합니다. -

중복 하위 트리는 -

이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- 배열 ret 생성, 맵 m 생성
- 재귀적 방법 solve()를 정의합니다. 이것은 노드를 입력으로 사용합니다. 이것은 다음과 같이 작동합니다 -
- 노드가 null이면 -1을 반환합니다.
- x :=노드의 값을 문자열로 지정한 다음 "#"을 연결합니다.
- left :=solve(노드의 왼쪽), right :=solve(노드의 오른쪽)
- x :=x 연결 "#" 왼쪽 연결, "#" 연결 오른쪽 연결
- m[x] 1 증가
- m[x]가 2이면 노드를 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, ]