|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=1261 lang=cpp |
| 3 | + * |
| 4 | + * [1261] Find Elements in a Contaminated Binary Tree |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +/** |
| 9 | + * Definition for a binary tree node. |
| 10 | + * struct TreeNode { |
| 11 | + * int val; |
| 12 | + * TreeNode *left; |
| 13 | + * TreeNode *right; |
| 14 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 15 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 16 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 17 | + * }; |
| 18 | + */ |
| 19 | + |
| 20 | +struct TreeNode { |
| 21 | + int val; |
| 22 | + TreeNode *left; |
| 23 | + TreeNode *right; |
| 24 | + TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 25 | + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 26 | + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 27 | + }; |
| 28 | + |
| 29 | +/** |
| 30 | + * Definition for a binary tree node. |
| 31 | + * struct TreeNode { |
| 32 | + * int val; |
| 33 | + * TreeNode *left; |
| 34 | + * TreeNode *right; |
| 35 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 36 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 37 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 38 | + * }; |
| 39 | + */ |
| 40 | +#include "bits/stdc++.h" |
| 41 | +using namespace std; |
| 42 | + |
| 43 | +class FindElements { |
| 44 | +public: |
| 45 | + FindElements(TreeNode* root) { |
| 46 | + |
| 47 | + if (!root) return; |
| 48 | + |
| 49 | + queue<TreeNode*> q; |
| 50 | + root->val = 0; |
| 51 | + q.emplace(root); |
| 52 | + visited.emplace(0); |
| 53 | + |
| 54 | + while(!q.empty()){ |
| 55 | + TreeNode* current = q.front(); |
| 56 | + q.pop(); |
| 57 | + |
| 58 | + if(current->left){ |
| 59 | + current->left->val = 2*current->val+1; |
| 60 | + q.push(current->left); |
| 61 | + visited.emplace(current->left->val); |
| 62 | + } |
| 63 | + if(current->right){ |
| 64 | + current->right->val = 2*current->val+2; |
| 65 | + q.push(current->right); |
| 66 | + visited.emplace(current->right->val); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + bool find(int target) { |
| 72 | + return visited.count(target); |
| 73 | + } |
| 74 | + private: |
| 75 | + unordered_set<int> visited; |
| 76 | +}; |
| 77 | + |
| 78 | +/** |
| 79 | + * Your FindElements object will be instantiated and called as such: |
| 80 | + * FindElements* obj = new FindElements(root); |
| 81 | + * bool param_1 = obj->find(target); |
| 82 | + */ |
| 83 | +// @lc code=end |
| 84 | + |
0 commit comments