Find Elements in a Contaminated Binary Tree - Problem
You are given a binary tree with the following rules:
root.val == 0- If
treeNode.val == xandtreeNode.left != null, thentreeNode.left.val == 2 * x + 1 - If
treeNode.val == xandtreeNode.right != null, thentreeNode.right.val == 2 * x + 2
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)Returnstrueif thetargetvalue exists in the recovered binary tree.
Input & Output
Example 1 — Basic Tree Recovery
$
Input:
root = [-1,-1,-1,-1,-1], operations = [["find",1],["find",3],["find",5]]
›
Output:
[true,true,false]
💡 Note:
Tree structure: root=0, left=1, right=2, left.left=3, left.right=4. Values 1 and 3 exist, but 5 does not.
Example 2 — Single Node Tree
$
Input:
root = [-1], operations = [["find",0],["find",1]]
›
Output:
[true,false]
💡 Note:
Only root exists with value 0. Value 1 would be left child but doesn't exist.
Example 3 — Larger Tree
$
Input:
root = [-1,-1,-1,-1,-1,-1,-1], operations = [["find",2],["find",6],["find",7]]
›
Output:
[true,true,false]
💡 Note:
Complete binary tree: 0→1,2→3,4,5,6. Values 2 and 6 exist, but 7 would be at position not in tree.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- At most 104 calls will be made to find
Visualization
Tap to expand
Understanding the Visualization
1
Contaminated Tree
All node values changed to -1
2
Recovery Formula
Apply root=0, left=2*x+1, right=2*x+2
3
Find Queries
Check if recovered values contain target
Key Takeaway
🎯 Key Insight: Use the parent-child formula to recover values and hash set for fast queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code