Skip to content

Create 1261. Find Elements in a Contaminated Binary Tree #722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions 1261. Find Elements in a Contaminated Binary Tree
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
}
};
Loading