↓Skip to main content
  1. LeetCode/

LeetCode 331: Verify Preorder Serialization of a Binary Tree

·2 mins· ·
LeetCode Medium String Stack Tree Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-10-25

  • Submissions: Accepted (first try)

Approach
#

There is no need to build the tree; just count how many open positions remain:

  • Start with 1 position, for the root.
  • Every node read, including #, fills 1 position.
  • A non-null node opens 2 more positions, for its children.

If the count goes negative midway, there are more nodes than positions; after reading everything the count must be exactly 0, or some position is left empty.

For 9,#,#,1: after 9,#,# the positions are used up, and reading 1 makes the count -1, so the answer is False.

My Attempts
#

Accepted on the first try.

Solution
#

class Solution:
    def isValidSerialization(self, preorder: str) -> bool:
        slots = 1
        for node in preorder.split(","):
            slots -= 1
            if slots < 0:
                return False
            if node != "#":
                slots += 2
        return slots == 0

Complexity
#

Time O(n), space O(n) for the split result (scanning characters directly gives O(1)).

Mistakes to Avoid
#

  • Subtract first, check for negative, and add 2 last. Adding 2 first accepts #,1,#, although the tree already ends at the first #.
  • Check for exactly 0 at the end, not just “never negative”.
  • Values can have several digits, so split on commas rather than treating each character as a node.

Interview Explanation
#

I count open slots instead of building the tree. There is one slot for the root, every node fills one, and a non-null node opens two. If the count goes negative midway it is invalid, and it must end at exactly zero. Time O(n). A stack version that keeps collapsing “number, #, #” into one # also works: valid if a single # remains.

Related

LeetCode 449: Serialize and Deserialize BST
·2 mins
LeetCode Medium String Tree Depth-First-Search Breadth-First-Search Design Binary-Search-Tree Binary-Tree
LeetCode 449 note: for a BST, pre-order without null markers is enough; deserialize recursively with bounds in O(n)
LeetCode 173: Binary Search Tree Iterator
·2 mins
LeetCode Medium Stack Tree Design Binary-Search-Tree Binary-Tree Iterator
LeetCode 173 note: flattening to an array is simple but uses O(n) space; the follow-up keeps the left spine on a stack for amortized O(1) and O(h) space
LeetCode 606: Construct String from Binary Tree
·1 min
LeetCode Medium String Tree Depth-First-Search Binary-Tree
LeetCode 606 note: output in pre-order, keeping an empty () when only the left subtree is missing, and omitting the right parentheses when it is empty
LeetCode 1028: Recover a Tree From Preorder Traversal
·3 mins
LeetCode Hard Tree Binary-Tree Dfs Stack String
LeetCode 1028 note: a stack holds the path from the root to the current node, so its length is the depth
LeetCode 297: Serialize and Deserialize Binary Tree
·2 mins
LeetCode Hard String Tree Depth-First-Search Breadth-First-Search Design Binary-Tree
LeetCode 297 note: pre-order with null markers identifies the tree uniquely; deserialize by consuming tokens from an iterator
LeetCode 450: Delete Node in a BST
·2 mins
LeetCode Medium Tree Binary-Search-Tree Binary-Tree
LeetCode 450 note: once the node is found: with zero or one child, splice the child in; with two, copy the right subtree’s minimum and delete that node