Verify Preorder Serialization of a Binary Tree (LeetCode 331): Solution and Explanation
Given a comma-separated preorder serialization where '#' marks a null child, decide whether it describes a real binary tree, without rebuilding the tree.
Intuition
Picture the tree as a set of empty positions waiting to be filled. Before reading anything there is one: the root.
Preorder fills positions one at a time. Every token, a value or '#', takes one position. A value also creates two new positions for its children, while '#' creates none.
So a single counter of open slots is enough. If a token shows up when no slot is open, the tree was already finished. If slots remain at the end, some node is missing a child.
Approach: Open slot counter
- Set
slots = 1for the root. - For each token: if
slots == 0, return false; otherwise use one slot (slots -= 1). - If the token is not '#', add two slots for its children.
- After all tokens, return
slots == 0.
Step-by-step example
preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
- Start with 1 slot. 9 uses it and opens 2: slots = 2. 3 and 4 do the same: slots = 4.
- '#', '#' close two slots (2 left). 1 opens two more (3), and '#', '#' close them (1 left).
- 2 uses the last slot and opens two (2). '#' closes one (1), 6 uses it and opens two (2), '#', '#' close them.
- All tokens are used and slots = 0, so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def isValidSerialization(self, preorder: str) -> bool:
3 slots = 1
4 for node in preorder.split(','):
5 if slots == 0:
6 return False
7 slots -= 1
8 if node != '#':
9 slots += 2
10 return slots == 01class Solution {
2 public boolean isValidSerialization(String preorder) {
3 int slots = 1;
4 for (String node : preorder.split(",")) {
5 if (slots == 0) {
6 return false;
7 }
8 slots--;
9 if (!node.equals("#")) {
10 slots += 2;
11 }
12 }
13 return slots == 0;
14 }
15}1class Solution {
2public:
3 bool isValidSerialization(string preorder) {
4 int slots = 1;
5 stringstream ss(preorder);
6 string node;
7 while (getline(ss, node, ',')) {
8 if (slots == 0) {
9 return false;
10 }
11 slots--;
12 if (node != "#") {
13 slots += 2;
14 }
15 }
16 return slots == 0;
17 }
18};Time and space complexity
O(n)
Each token is looked at once.
O(n)
Splitting the string stores the tokens. Scanning the characters directly brings this down to O(1).
Other approaches
Stack collapse (time O(n), space O(n))
Push tokens on a stack; whenever the top is '#', '#' over a value, replace those three with a single '#'. The string is valid if the stack ends as exactly one '#'.
Indegree and outdegree (time O(n), space O(1))
Treat the root as having one incoming edge for free. Each node adds one incoming edge, and each value adds two outgoing ones. Track out - in; it must never go negative and must end at 0. It is the same counter seen from a graph angle.
Common mistakes
- Checking the counter only at the end. In "#,1,#" the root slot is closed by the first '#', so 1 has no slot, yet a naive count goes 1, 0, 1, 0 and ends at 0. Stop as soon as a token arrives with no slot open.
- Treating multi-digit values character by character. Split on commas so "100" is one token.
- Returning true for "1" because nothing went negative. A lone value still has two open child slots.
Frequently asked questions
Why is "#" by itself valid?
It is the serialization of an empty tree: the single root slot is filled with null and no slots remain.
Why must the check happen before decrementing?
A token that arrives when slots is already 0 has nowhere to go. Without that early check, "#,1,#" would end with slots = 0 and be wrongly accepted.
Do the node values matter?
No. Only whether each token is a value or '#' matters for the shape of the tree.