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
Difficulty
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
AI Disclaimer
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.
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 toaddreceives a falsy node, the conditional block is skipped, and the set remains empty. Subsequentfindcalls 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
Nonebranches. - 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
setleverages 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 2236: Root Equals Sum of Children
- problem 1123: Lowest Common Ancestor of Deepest Leaves
- problem 1305: All Elements in Two Binary Search Trees
- problem 1609: Even Odd Tree
- problem 1980: Find Unique Binary String
- problem 2380: Time Needed to Rearrange a Binary String
- problem 2476: Closest Nodes Queries in a Binary Search Tree
Extra
- 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