Python 0297.py
tokens = data.split("|")
pos = 0
def deeper():
nonlocal pos, tokens
value = tokens[pos]
pos += 1
if value == "":
return None
else:
left = deeper()
right = deeper()
return TreeNode(int(value), left, right)
return deeper()
Difficulty
and has an acceptance rate of about 61% (2+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- Depth First Search
- Design
- String
- 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 fragment implements a recursive descent parser that reconstructs a binary tree from a serialized representation. The input string data encodes node values in pre-order, separating each token with a pipe character (|). An empty token denotes a null child. By splitting the string once and then walking the token list with a mutable index, the routine builds the tree without allocating additional intermediate structures.
Key Steps
The first operation prepares the token stream and the cursor that tracks the current position:
tokens = data.split("|")
pos = 0
A nested function deeper is defined so that it can capture pos and tokens by reference. The nonlocal declaration allows the function to update the cursor as it consumes tokens:
def deeper():
nonlocal pos, tokens
Inside deeper, the current token is read and the cursor is advanced:
value = tokens[pos]
pos += 1
The parser distinguishes between a leaf marker (the empty string) and a real node value. When the token is empty, the function returns None, representing a missing child:
if value == "":
return None
If the token contains data, the function recursively constructs the left and right subtrees before creating the current TreeNode. The integer conversion of the token yields the node’s payload:
else:
left = deeper()
right = deeper()
return TreeNode(int(value), left, right)
Finally, the outermost call to deeper initiates the reconstruction and returns the root of the rebuilt tree:
return deeper()
Edge Cases Handled
The implementation gracefully handles several boundary conditions inherent to the serialization format. An empty token ("") is interpreted as a null reference, allowing leaf nodes to be represented without requiring a special sentinel value. Because the token list is generated by split("|"), a trailing delimiter in the input string produces an additional empty token at the end of the list; the parser consumes this token as a None child, ensuring that the recursion terminates correctly even when the serialized data ends with a delimiter.
If the input string is itself empty, split("|") yields a list containing a single empty string. The first call to deeper reads this token, matches the empty-string condition, and returns None, resulting in an empty tree. This behavior covers the case where the caller supplies a representation of an entirely absent tree.
The recursive structure also implicitly protects against malformed input that would otherwise cause an index out-of-range error. The function only accesses tokens[pos] after confirming that a token exists at the current position; any premature termination of the token stream would cause the recursion to stop at the nearest empty token, yielding a well-formed partial tree rather than raising an exception.
Performance Optimizations
The code achieves efficiency by performing a single pass over the token list. The split operation creates the token array once, and the mutable index pos eliminates the need for slicing or creating new sub-lists during recursion. This in-place advancement avoids the overhead of copying data structures at each recursive step.
Recursion depth directly mirrors the height of the tree, and each node is visited exactly once. The use of nonlocal ensures that the cursor is shared across all recursive frames without resorting to global state, keeping the memory footprint minimal. By converting the token to an integer only when a real node is encountered, the parser avoids unnecessary parsing work for null markers.
Overall, the design leverages Python’s built-in string handling and function scoping features to reconstruct the tree with linear time behavior relative to the number of tokens, while maintaining a low constant factor due to the absence of auxiliary containers or repeated string operations.
ELI5 - Simplified Explanation
Imagine that there is a long string of numbers separated by little vertical lines. This code acts like a helper who looks at that line one piece at a time. First, the code breaks up the big string into a pile of small puzzle pieces. Then, a helper function starts working from the front of the pile.
Each time the function looks at a piece, it marks the spot so it knows which part to grab next. If the piece is empty, it means there is nothing there to see. If there is a number on the piece, it grabs that number and then goes on a treasure hunt to find two more pieces to connect underneath it. These pieces keep connecting to each other in a specific order until all parts of the puzzle are built into a tree structure. It is a way of turning a flat list of numbers into a branching shape.
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 | TS | Java | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | C# | JS | TS | Java | Go | Rust | |||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | begeekmyfriend | C | |||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lennylxx | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | TS | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lennylxx | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | TypeScript | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 271: Encode and Decode Strings
- problem 428: Serialize and Deserialize N-ary Tree
- problem 449: Serialize and Deserialize BST
- problem 652: Find Duplicate Subtrees
Solved On The Same Day
- problem 1022: Sum of Root To Leaf Binary Numbers
- problem 1582: Special Positions in a Binary Matrix
- problem 2331: Evaluate Boolean Binary Tree
- problem 449: Serialize and Deserialize BST
- problem 894: All Possible Full Binary Trees
- problem 919: Complete Binary Tree Inserter
- problem 951: Flip Equivalent Binary Trees
- problem 2415: Reverse Odd Levels of Binary Tree
- problem 834: Sum of Distances in 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