Problem 297

Abstract / Summary

Design methods to convert a binary tree to a string and back without using extra data structures.

Note

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

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()
16 lines | 397 bytes | submitted December 13, 2023 | GitHub  

Difficulty

This problem is ranked as
easy medium hard

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
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.56 | σ = 1.75

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 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
50 links | 33 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Serialize and Deserialize Binary Tree - Preorder Traversal - Leetcode 297 - Python'
NeetCode 14 mins
Serialize and Deserialize Binary Tree - Preorder Traversal - Leetcode 297 - Python
YouTube video '[Java] Leetcode 297. Serialize and Deserialize Binary Tree [Binary Tree #9]'
Eric Programming 14 mins
[Java] Leetcode 297. Serialize and Deserialize Binary Tree [Binary Tree #9]
YouTube video 'LeetCode 297 Serialize and Deserialize Binary Tree Explanation and Solution'
happygirlzt 8 mins
LeetCode 297 Serialize and Deserialize Binary Tree Explanation and Solution
YouTube video 'Serialize and Deserialize Binary Tree: 297 - Tree technical interview, @ Google, apple, Amazon, meta'
Destination FAANG 11 mins
Serialize and Deserialize Binary Tree: 297 - Tree technical interview, @ Google, apple, Amazon, meta
YouTube video 'LeetCode 297 Serialize and Deserialize Binary Tree 中文解释 Chinese Version'
happygirlzt 9 mins
LeetCode 297 Serialize and Deserialize Binary Tree 中文解释 Chinese Version
YouTube video 'Leetcode 297 Serialize and Deserialize Binary Tree Java | Interview Prep'
HackerHeap 19 mins
Leetcode 297 Serialize and Deserialize Binary Tree Java | Interview Prep
YouTube video 'Leetcode 297 - Serialize And Deserialize Binary Tree (JAVA Solution Explained!)'
LC Bear 9 mins
Leetcode 297 - Serialize And Deserialize Binary Tree (JAVA Solution Explained!)
YouTube video '297. Serialize and Deserialize Binary Tree (Leetcode Hard)'
Programming Live with Larry 7 mins
297. Serialize and Deserialize Binary Tree (Leetcode Hard)
YouTube video 'Facebook Coding Interview Question | Leetcode 297 | Serialize and Deserialize Binary Tree'
WorkWithGoogler 22 mins
Facebook Coding Interview Question | Leetcode 297 | Serialize and Deserialize Binary Tree
YouTube video 'Leetcode 297: Serialize and Deserialize Binary Tree in Telugu | BFS Approach | Python DSA | SRKCodes'
Srk Codes 20 mins
Leetcode 297: Serialize and Deserialize Binary Tree in Telugu | BFS Approach | Python DSA | SRKCodes
YouTube video 'Leetcode 297. Serialize and Deserialize Binary Tree [ JAVASCRIPT ].'
Web Fusion with Bharadwaj 4 mins
Leetcode 297. Serialize and Deserialize Binary Tree [ JAVASCRIPT ].
YouTube video '109. Leetcode 297. Serialize and Deserialize Binary Tree : JAVA'
Web Fusion with Bharadwaj 26 mins
109. Leetcode 297. Serialize and Deserialize Binary Tree : JAVA
YouTube video 'Serialize and Deserialize Binary Tree - LeetCode #297 - C++'
Sean Chuah 8 mins
Serialize and Deserialize Binary Tree - LeetCode #297 - C++
YouTube video '59. Leetcode 297. Serialize and Deserialize Binary Tree : Javascript'
Web Fusion with Bharadwaj 23 mins
59. Leetcode 297. Serialize and Deserialize Binary Tree : Javascript
YouTube video 'Serialize and Deserialize Binary Tree - Leetcode 297 | Using Preorder Traversal'
Code With K5KC 16 mins
Serialize and Deserialize Binary Tree - Leetcode 297 | Using Preorder Traversal
YouTube video 'leetcode 297  Serialize and Deserialize Binary Tree | traversal, recursion'
Code-Yao 12 mins
leetcode 297 Serialize and Deserialize Binary Tree | traversal, recursion
YouTube video '34. Leetcode 297. Serialize and Deserialize Binary Tree  : JAVA'
Web Fusion with Bharadwaj 26 mins
34. Leetcode 297. Serialize and Deserialize Binary Tree : JAVA
YouTube video 'Serialize and Deserialize Binary Tree - Leetcode 297 - Python'
Adam Djellouli 34 mins
Serialize and Deserialize Binary Tree - Leetcode 297 - Python
YouTube video 'LeetCode 297 | Serialize and Deserialize Binary Tree | Conversion | Java'
Sleepy Cracker 8 mins
LeetCode 297 | Serialize and Deserialize Binary Tree | Conversion | Java
YouTube video 'Serialize and Deserialize Binary Tree, Hard, C++, LeetCode'
H William Polenz 148 mins
Serialize and Deserialize Binary Tree, Hard, C++, LeetCode
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

10 solutions   December 13, 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