在 C++ 中查詢汙染二叉樹中的元素
假設我們有一個二叉樹。該樹的規則如下:
根節點的值為 0
如果樹節點的值為 x 且樹節點的左子節點不為空,則樹節點的左子節點的值為 2 * x + 1
如果樹節點的值為 x 且樹節點的右子節點不為空,則樹節點的右子節點的值為 2 * x + 2
現在,由於二叉樹被汙染了。這意味著樹節點的所有值都已更改為 -1。我們必須首先恢復二叉樹,然後實現 FindElements 類,如下所示:
FindElements(TreeNode* root) 使用汙染的二叉樹初始化物件,我們必須首先恢復它。
bool find(int target)。這將返回目標值是否存在於恢復的二叉樹中。
所以如果樹是這樣的:

因此,在恢復之後,如果我們嘗試查詢 1、3 和 5,則結果將分別為 true、true 和 false。
為了解決這個問題,我們將遵循以下步驟:
定義一個集合 a
定義一個 dfs() 方法,它將接收根節點和 rootVal。rootVal 最初為 -1
如果根節點為空,則返回
如果 rootVal 為 -1,則將根節點的值設定為 0,否則將其設定為 rootVal
將根節點的值插入到 a 中
呼叫 dfs(根節點的左子節點, 2 * 根節點的值 + 1), dfs(根節點的右子節點, 2 * 根節點的值 + 2)
對於初始化(或重建),我們將呼叫 dfs(根節點, -1)
要查詢某個元素,請檢查該元素是否在 a 中,如果在則返回 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP