From 069a802efcdad495b53715fe4f7d8f118bcd2411 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Fri, 21 Feb 2025 23:57:53 +0530 Subject: [PATCH] Create 1261. Find Elements in a Contaminated Binary Tree --- ...ind Elements in a Contaminated Binary Tree | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 1261. Find Elements in a Contaminated Binary Tree diff --git a/1261. Find Elements in a Contaminated Binary Tree b/1261. Find Elements in a Contaminated Binary Tree new file mode 100644 index 0000000..b406dd1 --- /dev/null +++ b/1261. Find Elements in a Contaminated Binary Tree @@ -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 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 + } +};