Verify Preorder Serialization of a Binary Tree - Problem

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. If it is a null node, we record using a sentinel value such as '#'.

For example, the binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node.

Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.

It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid.

Note: You are not allowed to reconstruct the tree.

Input & Output

Example 1 — Valid Serialization
$ Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true
💡 Note: This represents a valid binary tree where root=9 has children 3 and 2. Node 3 has children 4 and 1. All leaves properly terminated with '#'.
Example 2 — Invalid Serialization
$ Input: preorder = "1,#"
Output: false
💡 Note: A non-null node must have exactly two children. Node 1 has only one child ('#'), missing the second child.
Example 3 — Single Null Node
$ Input: preorder = "#"
Output: true
💡 Note: A single null node is a valid empty tree serialization.

Constraints

  • 1 ≤ preorder.length ≤ 104
  • preorder consist of integers and '#' separated by commas ','.

Visualization

Tap to expand
Preorder Serialization Validation"9,3,4,#,#,1,#,#,2,#,6,#,#"Input: Preorder traversal string932416Valid Tree Structure:✓ Each non-null has 2 children✓ Correct number of null nodes✓ All tokens consumedtrueOutput: Boolean indicating validity
Understanding the Visualization
1
Input
Comma-separated preorder traversal with '#' for null nodes
2
Validation
Check if it represents a valid binary tree structure
3
Output
Return true if valid, false otherwise
Key Takeaway
🎯 Key Insight: Track slot balance - each node uses 1 slot, non-null nodes create 2 slots
Asked in
Google 42 Amazon 38 Microsoft 25 Facebook 22
89.4K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen