Skip to main content

Find Elements in a Contaminated Binary Tree - Solution & Explanation

MediumHash TableTreeDepth-First SearchBreadth-First Search20 min readAsked at: Amazon, Google
Practice this problem

Problem Statement

Given a binary tree with the following rules:

  1. root.val == 0
  2. If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1
  3. 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.

 

Example 1:

Input
["FindElements","find","find"]
[[[-1,null,-1]],[1],[2]]
Output
[null,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1]); 
findElements.find(1); // return False 
findElements.find(2); // return True 

Example 2:

Input
["FindElements","find","find","find"]
[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
Output
[null,true,true,false]
Explanation
FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False

Example 3:

Input
["FindElements","find","find","find","find"]
[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
Output
[null,true,false,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True

 

Constraints:

  • TreeNode.val == -1
  • The height of the binary tree is less than or equal to 20
  • The total number of nodes is between [1, 104]
  • Total calls of find() is between [1, 104]
  • 0 <= target <= 106

Approach Overview

Problem Overview: You are given a binary tree where every node value has been contaminated and set to -1. The original tree followed a rule: the root was 0, the left child of value x was 2x + 1, and the right child was 2x + 2. Your task is to recover the tree and design a structure that efficiently checks whether a target value exists in it.

Approach 1: Recursive Tree Reconstruction (DFS) (Time: O(n), Space: O(n))

Start from the root and restore values using the rule that defines the original tree. Set the root to 0, then recursively assign 2x + 1 to the left child and 2x + 2 to the right child while traversing with Depth-First Search. During reconstruction, store every recovered value in a Hash Table or set. The find(target) operation becomes a constant-time lookup in the set. This approach is clean and natural because the recursive traversal mirrors the structure of the tree.

Approach 2: BFS Iterative Tree Recovery (Time: O(n), Space: O(n))

Instead of recursion, recover the tree level by level using a queue and Breadth-First Search. Initialize the root with value 0, push it into the queue, and iteratively process nodes while assigning values to children using the same formula. Each recovered value is inserted into a hash set for fast membership checks. BFS is useful if you want to avoid recursion depth limits or prefer an iterative traversal pattern when working with a Binary Tree.

Recommended for interviews: Recursive DFS reconstruction with a hash set is the most common solution. It clearly demonstrates understanding of tree traversal and the recovery formula while giving O(1) query time for find(). BFS is equally optimal but usually presented as an alternative implementation style.

Approach 1: Recursive Tree Reconstruction

This approach involves recursively traversing the contaminated binary tree and recovering the node values as per the given rules. As we traverse the tree, we will populate a set with the recovered values to allow efficient lookup for the find function.

In this implementation, we define a TreeNode structure and a FindElements object to hold the reference to the root and an array representing the possible values.

The recoverTree function is used recursively to traverse and recover the tree by assigning node values based on the rules and storing them in the boolean array.

The findElementsFind function simply checks if the target value exists in the tree by checking its presence in the array.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the number of nodes in the tree, as we visit each node once to recover it.

Space Complexity: O(n) for storing the node values in a boolean array.

Try this approach in the editor →

Approach 2: BFS Iterative Tree Recovery

Utilizing a breadth-first search (BFS) strategy offers a way to recover and parse through the tree's nodes iteratively. Through this approach, we harness a queue to manage node processing, ensuring we systematically visit each node layer by layer.

This C implementation showcases the BFS strategy, using an array-based queue for managing node visits. The bfsRecover function assigns and verifies values for the binary tree nodes iteratively, keeps record in a boolean array, and the findElementsFind checks the target against this recovered array.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) given each node is examined once for value set-up and recovery.

Space Complexity: O(n) due to usage of a queue to store nodes and a boolean array of node values.

Try this approach in the editor →

Approach 3: DFS + Hash Table

First, we traverse the binary tree using DFS, restore the node values to their original values, and store all node values in a hash table. Then, when searching, we only need to check if the target value exists in the hash table.

In terms of time complexity, it takes O(n) time to traverse the binary tree during initialization, and O(1) time to check if the target value exists in the hash table during search. The space complexity is O(n), where n is the number of nodes in the binary tree.

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Recursive Tree Reconstruction

Time Complexity: O(n), where n is the number of nodes in the tree, as we visit each node once to recover it.

Space Complexity: O(n) for storing the node values in a boolean array.

BFS Iterative Tree Recovery

Time Complexity: O(n) given each node is examined once for value set-up and recovery.

Space Complexity: O(n) due to usage of a queue to store nodes and a boolean array of node values.

DFS + Hash Table—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive Tree Reconstruction (DFS)O(n)O(n)Clean implementation when recursion is acceptable and you want a straightforward recovery process
BFS Iterative Tree RecoveryO(n)O(n)Preferred when avoiding recursion or when implementing tree traversal iteratively

Video Solution

Find Elements in a Contaminated Binary Tree | BFS | DFS | Leetcode 1261 | codestorywithMIK • codestorywithMIK • 7,457 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Find Elements in a Contaminated Binary Tree easy or hard?
The problem is rated Medium because it combines binary tree traversal with a small design component. Understanding the value-generation formula is straightforward, but implementing efficient preprocessing and query handling requires familiarity with tree algorithms and hash sets.
Find Elements in a Contaminated Binary Tree Python/Java solution
Both Python and Java implementations reconstruct the tree and insert recovered values into a HashSet or set. The constructor performs DFS or BFS to compute node values, and the find(target) method simply checks whether the set contains the target.
How to solve Find Elements in a Contaminated Binary Tree in O(n)?
Traverse the contaminated tree once and reconstruct node values using the rules root=0, left=2x+1, and right=2x+2. Use DFS or BFS to visit each node and store the computed value in a hash set. After preprocessing, checking whether a target exists becomes a constant-time membership test.
What is the best approach for Find Elements in a Contaminated Binary Tree?
The best approach is to reconstruct the tree using DFS or BFS and store all recovered values in a hash set. Reconstruction takes O(n) time, and each find(target) query becomes an O(1) hash lookup. This design matches the expected solution pattern in interviews and coding platforms.
Is Find Elements in a Contaminated Binary Tree asked at Google/Amazon/Meta?
Tree reconstruction and design problems like this commonly appear in interviews at companies such as Amazon, Google, and Meta. Variations often test understanding of binary tree traversal, value propagation rules, and designing efficient query operations.
What data structure is used in Find Elements in a Contaminated Binary Tree?
The main data structures are a binary tree for reconstruction and a hash set for fast lookups. DFS uses recursion with the call stack, while BFS uses a queue to process nodes level by level. The hash set ensures O(1) average-time queries.
What is the time complexity of Find Elements in a Contaminated Binary Tree?
Recovering the entire tree requires visiting every node once, so preprocessing takes O(n) time. Each call to find(target) runs in O(1) time using a hash set lookup. The space complexity is O(n) for storing recovered values.

Ready to solve this problem?

Practice Find Elements in a Contaminated Binary Tree with our built-in code editor and test cases.

Practice on FleetCode