Find Elements in a Contaminated Binary Tree - Problem

You are given a binary tree with the following rules:

  • root.val == 0
  • If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1
  • If treeNode.val == x and treeNode.right != null, then treeNode.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) Returns true if the target value 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
Contaminated Binary Tree RecoveryContaminated-1-1-1Recovery Rulesroot.val = 0left = 2*parent + 1right = 2*parent + 2Recovered012Query Processingfind(1) → truefind(2) → trueStore recovered values in hash set for O(1) lookup
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
Asked in
Facebook 15 Google 12 Amazon 8
12.5K Views
Medium Frequency
~15 min Avg. Time
428 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen