이진 트리가 있다고 가정합니다. 해당 트리의 규칙은 다음과 같습니다 -
-
root.val ==0
-
treeNode.val이 x이고 treeNode.left가 null이 아닌 경우 treeNode.left.val =2 * x + 1
-
treeNode.val이 x이고 treeNode.right가 null이 아닌 경우 treeNode.right.val =2 * x + 2
이제 이진 트리가 오염되었습니다. 이것은 트리 노드의 모든 val이 -1로 변경되었음을 나타냅니다. 먼저 이진 트리를 복구한 다음 다음과 같이 FindElements 클래스를 구현해야 합니다. -
-
FindElements(TreeNode* root) 오염된 바이너리 트리로 개체를 초기화합니다. 먼저 복구해야 합니다.
-
부울 찾기(int 대상). 복구된 이진 트리에 대상 값이 있는 경우 반환됩니다.
트리가 다음과 같다면 -

따라서 복구 후 1, 3, 5를 찾으려고 하면 결과가 참, 참, 거짓이 됩니다.
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
세트 정의
-
dfs() 메서드를 정의하면 루트가 되고 rootVal이 됩니다. rootVal은 처음에 -1입니다.
-
루트가 null이면 반환
-
rootVal이 -1이면 root 값을 0으로 설정하고 그렇지 않으면 rootVal로 설정
-
루트 값을
에 삽입 -
dfs(루트의 왼쪽, 2* 루트의 값 + 1), dfs(루트의 오른쪽, 2* 루트의 값 + 2) 호출
-
초기화(또는 재구성)를 위해 dfs(root, -1)
를 호출합니다. -
어떤 요소를 찾으려면 요소가 있는지 여부를 확인하십시오. 그렇다면 true를 반환하고 그렇지 않으면 false를 반환합니다.
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
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;
}
class FindElements {
public:
set <int> a;
void dfs(TreeNode* root,int rootVal=-1){
if(!root)return;
root->val = rootVal == -1?0:rootVal;
a.insert(root->val);
dfs(root->left,2*root->val + 1);
dfs(root->right, 2*root->val + 2);
}
FindElements(TreeNode* root) {
dfs(root);
}
bool find(int t) {
return a.find(t)!=a.end();
}
};
main(){
vector<int> v = {-1,-1,-1,-1,-1};
TreeNode *root = make_tree(v);
FindElements ob(root);
cout << (ob.find(1)) << endl;
cout << (ob.find(3)) << endl;
cout << (ob.find(5)) << endl;
} 입력
Initialize the tree with [-1,-1,-1,-1,-1], then call find(1), find(3) and find(5)
출력
1 1 0