Problem 331 · LeetCode 331(opens in a new tab)
Verify Preorder Serialization of a Binary Tree
MediumStacks
A binary tree can be written down in preorder: visit a node, then its left subtree, then its right subtree. Each real node is written as its value, and each missing child as #. The tokens are joined by commas.
You get such a string, preorder. Return true if it describes a real binary tree, and false if it cannot. Every token is a number or #, and the commas are well formed. Try to answer without building the tree.
Example 1
Input: preorder = "3,1,#,#,4,#,8,#,#" Output: true Why: 3 has leaf 1 on the left, and 4 (with right child 8) on the right
2 more examples and the constraints
Example 2
Input: preorder = "2,#" Output: false Why: 2 needs two children; only one is given
Example 3
Input: preorder = "4,#,#,7" Output: false Why: the tree ends after "4,#,#"; 7 is left over
Constraints
- 1 ≤ length of preorder ≤ 10,000
- Each token is
#or a whole number from 0 to 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Stack, fold finished subtreesO(n)
- Count the open slotsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 characters | Verdict |
|---|---|---|---|
| Stack, fold finished subtrees | O(n) | Passes; O(n) stack | |
| Count the open slots | O(n) | Best; one counter |
n = number of tokens. Both read each token once.
Edge cases to test
- Just "#". An empty tree is valid: one slot, filled by the null.
- Leftover tokens. "4,#,#,7" completes the tree and then has more: false.
- Missing nulls. "2,#" or "1" leave open slots at the end: false.
- Multi-digit values. "100" is one token; split on commas, not on characters.
- Null first. "#,1,#" ends the tree at once, so 1 is extra, even though the count ends at 0.
Common mistakes
- Checking only that the count ends at 0: "#,1,#" ends at 0 but the tree was already complete after the first #.
- Reading the string character by character and treating "100" as three values.
- In Java, comparing a token with "#" using == instead of equals, which compares references.
How to talk through it
- 1Clarify. Is "#" alone valid? Can values have several digits? Am I allowed to build the tree?
- 2Fold with a stack. A finished leaf looks like value, #, # and can be replaced by one #.
- 3Count slots instead. Each token fills one slot and each value opens two; the root starts with one.
- 4Code the counter. Fail if a token arrives with no slot left; succeed if the slots end at 0.
- 5Test out loud. Run "#", "2,#" and "4,#,#,7".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?