This is the daily question of leetcode in 2025-02-21. {: .prompt-info }
Problem Description #
Given a binary tree with the following rules:
root.val == 0
- For any
treeNode
:- If
treeNode.val
has a valuex
andtreeNode.left != null
, thentreeNode.left.val == 2 * x + 1
- If
treeNode.val
has a valuex
andtreeNode.right != null
, thentreeNode.right.val == 2 * x + 2
- If
Now the binary tree is contaminated, which means all treeNode.val
have been changed to -1
.
Implement the FindElements
class:
FindElements(TreeNode* root)
Initializes the object with a contaminated binary tree and recovers it.bool find(int target)
Returnstrue
if thetarget
value exists in the recovered binary tree.
Intuition #
- We traverse all the nodes of the tree and update their values to satisfy the constraints given in the problem.
- After modifying the values, we store them in a hash map to keep track of which values exist in the tree.
Code #
class FindElements {
private:
unordered_map<int, bool> exist;
void dfs(TreeNode* root, int val){
if(!root){
return;
}
else{
root->val = val;
exist[val] = true;
}
dfs(root->left, 2 * val + 1);
dfs(root->right, 2 * val + 2);
}
public:
FindElements(TreeNode* root) {
dfs(root, 0);
}
bool find(int target) {
return exist[target];
}
};
Thank you for reading! Let me know your thoughts and feedback! {: .prompt-tip }