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
Verify Preorder Serialization of Binary Tree INPUT Preorder String Represents: 9 3 2 4 1 6 # # # # # # # preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Node # = Null ALGORITHM: Degree Counting 1 Initialize degree = 1 Root needs 1 slot 2 For each node: degree-- (consume slot) 3 If non-null node: degree += 2 (add 2 slots) 4 Check validity: degree must never go < 0 Degree Changes 9: 1-1+2=2 3: 2-1+2=3 4: 3-1+2=4 #: 4-1=3 #: 3-1=2 1: 2-1+2=3 #: 3-1=2 #: 2-1=1 2: 1-1+2=2 #: 2-1=1 6: 1-1+2=2 #: 2-1=1 #: 1-1=0 FINAL RESULT Degree tracking graph: 4 3 2 1 0 Processing each node Output: true Validation: OK Final degree = 0 Never went negative Key Insight: In a valid binary tree, each non-null node provides 2 slots (for children) and consumes 1 slot (as a child). Each null (#) only consumes 1 slot. The total degree must end at 0 and never go negative during traversal. This avoids rebuilding the tree while validating the serialization format in O(n) time. TutorialsPoint - Verify Preorder Serialization of a Binary Tree | Degree Counting Approach
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