Verify Preorder Serialization of Binary Tree

Medium

Description

Given a string of comma-separated values representing preorder traversal, verify if it represents a valid serialization of a binary tree.

Examples

Input:preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output:true
Explanation:

Valid serialization.

Input:preorder = "1, arg2 = #"
Output:false
Explanation:

For preorder = "1, arg2 = #", the answer is false because the verify preorder serialization of binary tree condition is not met.

Input:preorder = "1,2,#,#,3,#,#"
Output:
Explanation:

This represents a valid binary tree with root 1, left child 2 (with two null children), and right child 3 (with two null children). Each non-null node is followed by exactly two children in preorder traversal.

Constraints

  • 1 ≤ preorder.length ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!