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