Leetcode #331: Verify Preorder Serialization of a Binary Tree
In this guide, we solve Leetcode #331 Verify Preorder Serialization of a Binary Tree in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Stack, Tree, String, Binary Tree
Intuition
The problem has a natural nested or last-in-first-out structure.
A stack lets us resolve matches in the correct order as we scan.
Approach
Push items as they appear and pop when you can finalize a decision.
The stack captures the unresolved part of the input.
Steps:
- Push elements as you scan.
- Pop when a rule or match is satisfied.
- Use the stack to compute results.
Example
Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true
Python Solution
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stk = []
for c in preorder.split(","):
stk.append(c)
while len(stk) > 2 and stk[-1] == stk[-2] == "#" and stk[-3] != "#":
stk = stk[:-3]
stk.append("#")
return len(stk) == 1 and stk[0] == "#"
Complexity
The time complexity is and the space complexity is , where is the length of the string preorder. The space complexity is , where is the length of the string preorder.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.