Skip to content

Commit a595e39

Browse files
authored
Create Find Elements in a Contaminated Binary Tree
1 parent e4aaad0 commit a595e39

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
想法:用 DFS 的方式重建整棵樹,並用 hash set 紀錄出現過的數字,未來查找時只需查看 hash set 中是否存在即可
2+
3+
Time Complexity : O(n) for constructing n nodes in the tree
4+
Space Complexity : O(n) for the hash set to store n numbers
5+
6+
7+
/**
8+
* Definition for a binary tree node.
9+
* struct TreeNode {
10+
* int val;
11+
* TreeNode *left;
12+
* TreeNode *right;
13+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
14+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
15+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
16+
* };
17+
*/
18+
class FindElements {
19+
public:
20+
unordered_set<int> appear ;
21+
void DFS(int x , TreeNode* root) {
22+
if ( x > 1e6 || !root )
23+
return ;
24+
25+
appear.insert(x) ;
26+
//cout << "insert : " << x << endl ;
27+
DFS(2 * x + 1 , root->left) ;
28+
DFS(2 * x + 2 , root->right) ;
29+
return ;
30+
}
31+
FindElements(TreeNode* root) {
32+
DFS(0 , root) ;
33+
}
34+
35+
bool find(int target) {
36+
return appear.find(target) != appear.end() ;
37+
}
38+
};
39+
40+
/**
41+
* Your FindElements object will be instantiated and called as such:
42+
* FindElements* obj = new FindElements(root);
43+
* bool param_1 = obj->find(target);
44+
*/

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy