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 Recovery INPUT Contaminated Tree (all -1) -1 -1 -1 -1 -1 root = [-1,-1,-1,-1,-1] Operations: find(1) find(3) find(5) ALGORITHM STEPS 1 Initialize HashSet Create set to store values 2 Recover Root root.val = 0, add to set 3 BFS/DFS Traversal left=2*x+1, right=2*x+2 4 Find = Set Lookup O(1) per query Recovered Tree: 0 1 2 3 4 HashSet {0} {1} {2} {3} {4} FINAL RESULT Query Results: find(1) --> true 1 exists in set find(3) --> true 3 exists in set find(5) --> false 5 NOT in set Output Array: [true, true, false] OK - All queries processed in O(1) Key Insight: By preprocessing the tree with BFS/DFS and storing all recovered values in a HashSet, we achieve O(n) initialization time and O(1) query time. The formulas left=2*x+1 and right=2*x+2 create a perfect binary tree numbering pattern that can be recovered from any contaminated state. TutorialsPoint - Find Elements in a Contaminated Binary Tree | Hash Set Preprocessing Approach
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