/331. Verify Preorder Serialization of a Binary Tree

331. Verify Preorder Serialization of a Binary Tree

Medium
Strings47.1% acceptance

Given a string input representing a preorder traversal serialization of a binary tree, where non-null nodes are represented by integer values and null nodes are represented by the character #, separated by commas, determine if the serialization is valid. You are not allowed to reconstruct the tree. The input format is guaranteed to be valid (e.g., no consecutive commas, all values are either integers or #). Return True if the serialization corresponds to a valid binary tree, otherwise return False.

Example 1

Input: 7,2,#,#,5,#,#

Output: True

Explanation: This serialization represents a valid binary tree.

Example 2

Input: 10,#,#,#

Output: False

Explanation: Too many nulls; not a valid binary tree.

Example 3

Input: 8,4,#,#,#

Output: True

Explanation: Valid binary tree serialization.

Example 4

Input: 3,#,4,#,#

Output: True

Explanation: Valid binary tree serialization.

Example 5

Input: 2,#,3,#,#,#

Output: False

Explanation: Too many nulls; not a valid binary tree.

Constraints

  • 1 <= len(serialized) <= 104
  • serialized consists of integers in the range [0, 100] and # separated by commas ,
  • Input format is always valid (no consecutive commas, all values are either integers or #)
Python (current runtime)

Case 1

Input: '1,2,#,#,3,#,#'

Expected: True

Case 2

Input: '5,#,#'

Expected: True

Case 3

Input: '6,#,7,#,#'

Expected: True

Case 4

Input: '4,#,#,5'

Expected: False

Case 5

Input: '9,#,#,#'

Expected: False