Verify Preorder Serialization of a Binary Tree - Problem

Imagine you have a binary tree that's been flattened into a string using preorder traversal - where we visit the root first, then the left subtree, then the right subtree. When we encounter a node with a value, we record it. When we hit a null pointer, we mark it with #.

For example, the tree:

    9
   / \
  3   2
 / \   \
4   1   6

becomes the serialized string: "9,3,4,#,#,1,#,#,2,#,6,#,#"

Your mission: Given a comma-separated string, determine if it represents a valid preorder serialization of some binary tree. You cannot reconstruct the actual tree - you must verify the structure using only the string!

The tricky part? Every valid binary tree serialization must have exactly the right number of null markers (#) in exactly the right positions. Too few nulls means incomplete leaf nodes, too many means extra dangling pointers.

Input & Output

example_1.py โ€” Valid Tree Serialization
$ Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
โ€บ Output: true
๐Ÿ’ก Note: This represents a valid binary tree. The preorder traversal visits: root(9), left subtree(3,4,#,#,1,#,#), right subtree(2,#,6,#,#). Each non-null node has exactly 2 children (which may be null), and the structure is properly balanced.
example_2.py โ€” Invalid - Missing Null
$ Input: preorder = "1,#"
โ€บ Output: false
๐Ÿ’ก Note: This is invalid because node 1 has only one child specified (#). In a proper binary tree serialization, every non-null node must have exactly 2 children (left and right), even if they are null. The correct serialization would be "1,#,#".
example_3.py โ€” Invalid - Extra Nodes
$ Input: preorder = "9,#,#,1"
โ€บ Output: false
๐Ÿ’ก Note: After processing "9,#,#" we have a complete tree (root with two null children). The extra "1" at the end makes this invalid - there's nowhere in the tree structure for this additional node to belong.

Constraints

  • 1 โ‰ค preorder.length โ‰ค 104
  • preorder consists of integers and '#' separated by commas
  • No consecutive commas (input format is always valid)
  • Each integer is in range [-1000, 1000]

Visualization

Tap to expand
Binary Tree Serialization Validation ProcessInput: "9,3,4,#,#,1,#,#,2,#,6,#,#"Stack State934##Collapse!After Collapse93#Tree Structure932##โœ“ Pattern: [parent, #, #] โ†’ [#] represents completed subtreeValid serialization ends with exactly one '#' in the stack
Understanding the Visualization
1
Parse the Recipe
Split the serialization string into individual components (nodes and null markers)
2
Stack Construction
Use a stack to simulate building the tree structure, adding each component as we encounter it
3
Identify Complete Subtrees
When we see a pattern of [parent, #, #], we know this subtree is complete and can be collapsed
4
Collapse and Validate
Replace completed subtrees with a single # and continue until we either finish with one # (valid) or get stuck (invalid)
Key Takeaway
๐ŸŽฏ Key Insight: Every non-null node contributes +1 to the 'degree balance' (creates 2 children, consumes 1 parent slot), while null nodes contribute -1. A valid tree maintains non-negative balance throughout and ends at exactly 0.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
32.0K Views
Medium-High Frequency
~18 min Avg. Time
1.4K 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