-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path1261. Find Elements in a Contaminated Binary Tree
53 lines (47 loc) · 1.65 KB
/
1261. Find Elements in a Contaminated Binary Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class FindElements {
public:
/**
* Recursively restores the values of the tree nodes.
* - The root starts with value `0`.
* - The left child of a node with value `x` is assigned `2 * x + 1`.
* - The right child of a node with value `x` is assigned `2 * x + 2`.
*/
void solve(TreeNode* root) {
if (root == NULL) {
return; // Base case: If the node is NULL, stop the recursion
}
// Store the restored value in the list
values_list.push_back(root->val);
// Process left child (if exists)
if (root->left != NULL) {
root->left->val = root->val * 2 + 1; // Assign new value
}
solve(root->left);
// Process right child (if exists)
if (root->right != NULL) {
root->right->val = root->val * 2 + 2; // Assign new value
}
solve(root->right);
}
vector<int> values_list; // Stores recovered values of the tree
/**
* Constructor initializes the recovery process of the tree.
* - The root node is set to `0`.
* - Calls `solve()` to restore the entire tree.
*/
FindElements(TreeNode* root) {
root->val = 0; // Initialize root value to 0
solve(root);
}
/**
* Checks if a given `target` value exists in the recovered tree.
* - Uses linear search to find the target in `values_list`.
* - Returns `true` if found, otherwise `false`.
*/
bool find(int target) {
for (int i = 0; i < values_list.size(); i++) {
if (target == values_list[i]) return true; // Target found
}
return false; // Target not found
}
};