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
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]