#1261

Find Elements in a Contaminated Binary Tree

Medium
Hash TableTreeDepth-First SearchBreadth-First SearchDesignBinary TreeHash MapTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a Depth-First Search (DFS) to recover the tree values and stores them in a HashSet for O(1) average time complexity during the find operation. This is efficient because we only traverse the tree once.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a HashSet to store recovered values.
  2. 2Step 2: Use a recursive DFS function to recover the tree values based on the rules.
  3. 3Step 3: For each call to find(target), check if the target exists in the HashSet.
solution.py14 lines
1class FindElements:
2    def __init__(self, root):
3        self.recovered = set()
4        self.recover(root, 0)
5
6    def recover(self, node, value):
7        if node:
8            node.val = value
9            self.recovered.add(value)
10            self.recover(node.left, 2 * value + 1)
11            self.recover(node.right, 2 * value + 2)
12
13    def find(self, target):
14        return target in self.recovered

Complexity note: The time complexity is O(n) because we traverse the tree once to recover the values. The space complexity is O(n) due to the HashSet storing the recovered values.

  • 1The recovery of the tree values follows a specific mathematical pattern based on the parent value.
  • 2Using a HashSet allows for efficient lookups.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.