1261: Find-Elements-in-a-Contaminated-Binary-Tree
Medium
I like my solution to today’s daily.
For FindElements
, you just execute a simple
BFS using a queue
to keep track of
each layer.
Then, for find
, realise that by adding
1
to target
, if we iterate through all
the bits (ignoring the most significant bit) from
the second most significant bit to the
least significant bit, we have a ‘path’, where a
0
bit signifies we take ptr->left
and
a 1
bit signifies we take
ptr->right
.
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class FindElements {
public:
* r;
TreeNode(TreeNode* root) {
FindElements= root;
r ->val = 0;
r<TreeNode*> q;
queue.push(r);
qwhile (q.size() != 0) {
int n = q.size();
for (int i = 0; i < n; ++i) {
* temp = q.front();
TreeNode.pop();
qif (temp->left) {
->left->val = 2*temp->val+1;
temp.push(temp->left);
q}
if (temp->right) {
->right->val = 2*temp->val+2;
temp.push(temp->right);
q}
}
}
}
bool find(int target) {
int n = floor(log2(target+1));
int path = target + 1;
int index = 0;
* ptr = r;
TreeNodefor (int i = n-1; i >= 0; --i) {
if (((1 << i) & path) != 0) {
if (ptr->right) {
= ptr->right;
ptr } else {
return false;
}
} else {
if (ptr->left) {
= ptr->left;
ptr } else {
return false;
}
}
}
return true;
}
};
/**
* Your FindElements object will be instantiated and called as such:
* FindElements* obj = new FindElements(root);
* bool param_1 = obj->find(target);
*/