Problem 1261

Abstract / Summary

Given a binary tree with certain nodes marked as contaminated, return all non contaminated node values in the order they are encountered during a traversal.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1261.py

class FindElements:
    def __init__(self, root: Optional[TreeNode]):
        self.all = set()
        self.add(root, 0)

    def add(self, node, id): # convert to hashed set
        if node:
            self.all.add(id)
            self.add(node.left,  2 * id + 1)
            self.add(node.right, 2 * id + 2)

    def find(self, target: int) -> bool:
        return target in self.all
13 lines | 400 bytes | submitted October 31, 2023 | GitHub   9% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 84% (200k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Design
  • Hash Table
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided class FindElements builds a hashed representation of a binary tree where each node’s value is derived from its position in a conceptual complete binary tree. The constructor walks the tree once, populating a Python set with integer identifiers that correspond to the recovered values. Subsequent find calls simply test membership in this set, yielding immediate answers.

Construction Phase

The __init__ method receives the root of the original tree. It creates an empty set named all and immediately invokes the helper add with the root node and an initial identifier of 0.

def __init__(self, root: Optional[TreeNode]):
    self.all = set()
    self.add(root, 0)

The identifier 0 represents the value that the root would have after the “recover” transformation described in the problem statement. By starting the recursion here, the entire tree is processed before any queries are made.

Recursive Population

The add method is the core of the preprocessing step. It receives a node reference and the integer identifier that the node should contribute to the set.

def add(self, node, id):
    if node:
        self.all.add(id)
        self.add(node.left,  2 * id + 1)
        self.add(node.right, 2 * id + 2)

When the node is not None, the method inserts the current identifier into self.all. It then recurses on the left child with the formula 2 * id + 1 and on the right child with 2 * id + 2. These formulas mirror the index calculation used for a binary heap stored in an array, guaranteeing a unique identifier for each position regardless of the tree’s shape.

Edge-case handling in recursion

  • Empty tree - If the supplied root is None, the initial call to add receives a falsy node, the conditional block is skipped, and the set remains empty. Subsequent find calls will correctly report that no values exist.
  • Sparse structures - Because the identifier calculation depends only on the path taken, missing children do not disrupt the sequence; the recursion simply does not descend into None branches.
  • Large depth - The recursion depth equals the height of the tree. The algorithm gracefully terminates when leaf nodes are reached, and the set continues to hold all identifiers generated up to that depth.

Query Phase

The find method checks whether a target integer appears in the pre-computed set.

def find(self, target: int) -> bool:
    return target in self.all

Since self.all is a hash-based collection, the membership test executes with minimal overhead, delivering an immediate Boolean result.

Performance Optimizations

The design incorporates several deliberate choices that improve runtime behavior:

  • Single traversal - All identifiers are generated in one depth-first pass during object construction. This eliminates repeated tree walks for each query, turning potentially linear-time searches into constant-time lookups.
  • Hash set for membership - Storing identifiers in a Python set leverages the language’s built-in hash table, providing rapid containment checks without additional indexing structures.
  • Arithmetic-based identifiers - By computing identifiers through simple integer arithmetic rather than storing explicit node values, the algorithm avoids extra memory for value fields and reduces the amount of data copied into the set.
  • Early termination on null nodes - The guard if node: prevents unnecessary recursive calls on absent children, keeping the call stack as shallow as possible for sparse trees.

Collectively, these techniques ensure that after the initial O(N) preprocessing (where N is the number of nodes), each find operation runs in constant time, and the memory footprint is proportional to the number of nodes, stored as compact integers.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant family tree where every person has a special number. At the very top, the first person starts with the number zero. Whenever someone has a child on their left side, that new child gets a number found by doubling the parent's number and adding one. If the child is on the right side, the new number is double the parent's number plus two.

This code works like a giant notebook. When the program starts, it walks through every branch of the entire tree to figure out what number belongs to each person. It writes all those numbers down into a collection to keep them organized. Once the notebook is full, checking if someone is in the family is very fast. When a specific number is asked for, the program simply looks through its notebook to see if that number is written inside.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.27 | σ = 0.90

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go TS
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
Shamik07 Dart
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
Shamik07 Dart
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
31 links | 18 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

8 solutions   October 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality