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:
    TreeNode* r;
    FindElements(TreeNode* root) {
        r = root;
        r->val = 0;
        queue<TreeNode*> q;
        q.push(r);
        while (q.size() != 0) {
            int n = q.size();
            for (int i = 0; i < n; ++i) {
                TreeNode* temp = q.front();
                q.pop();
                if (temp->left) {
                    temp->left->val = 2*temp->val+1;
                    q.push(temp->left);
                }
                if (temp->right) {
                    temp->right->val = 2*temp->val+2;
                    q.push(temp->right);
                }
            }
        }
    }

    bool find(int target) {
        int n = floor(log2(target+1));
        int path = target + 1;
        int index = 0;
        TreeNode* ptr = r;
        for (int i = n-1; i >= 0; --i) {
            if (((1 << i) & path) != 0) {
                if (ptr->right) {
                    ptr = ptr->right;
                } else {
                    return false;
                }
            } else {
                if (ptr->left) {
                    ptr = ptr->left;
                } 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);
 */

Complexity:

Learnings:

Time Taken: