Verify Preorder Serialization of a Binary Tree (LeetCode 331): Solution and Explanation

Medium
String
Stack
Tree
Binary Tree

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

  1. Set slots = 1 for the root.
  2. For each token: if slots == 0, return false; otherwise use one slot (slots -= 1).
  3. If the token is not '#', add two slots for its children.
  4. After all tokens, return slots == 0.

Step-by-step example

preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
  1. Start with 1 slot. 9 uses it and opens 2: slots = 2. 3 and 4 do the same: slots = 4.
  2. '#', '#' close two slots (2 left). 1 opens two more (3), and '#', '#' close them (1 left).
  3. 2 uses the last slot and opens two (2). '#' closes one (1), 6 uses it and opens two (2), '#', '#' close them.
  4. 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 == 0
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each token is looked at once.

Space

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.