Skip to content

← leetcode

Find Elements in a Contaminated Binary Tree

· Medium

LeetCode problem 1261

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.

  • if this 'path' leads to an existing TreeNode, then we can return True
  • if this 'path' leads to an non-existant TreeNode, then we can return False

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

  • Time: O(n) for FindElements, O(log n) for find
  • Space: O(1)

learnings

  • log2 exists I guess?

time taken

  • 36 minutes and 35.50 seconds
    • I swear your goat is not washed; he was just tired today
    • I guess there is also a solution using a hashmap with O(1) Time Complexity and O(n) Space Complexity that is also significantly easier to code...