We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Verify Preorder Serialization of a Binary Tree

Difficulty: Medium


Problem Description

Given a string of comma-separated values representing a preorder traversal of a binary tree, return true if it is a correct serialization of a binary tree. Non-null nodes are represented by their values, while null nodes are represented by a sentinel value '#'.


Key Insights

  • The preorder traversal follows the pattern: root, left subtree, right subtree.
  • Each non-null node adds two potential positions for children (left and right), while each null node consumes one position.
  • The final count of available slots for nodes must be zero for the serialization to be valid.

Space and Time Complexity

Time Complexity: O(n), where n is the number of nodes in the tree (or the number of elements in the input string). Space Complexity: O(1), as we are using a constant amount of space for variables, regardless of the input size.


Solution

To solve the problem, we will iterate through the serialized string and maintain a count of available slots for nodes. Each time we encounter a non-null node, we will increase the count of available slots by one (for the node itself) and decrease it by two (for the two children it can have). For each null node, we simply decrease the count by one. At the end of the traversal, if we have exactly zero slots left, the serialization is valid.

We can implement this using a simple integer counter.


Code Solutions

def isValidSerialization(preorder: str) -> bool:
    slots = 1  # Start with one slot for the root node
    nodes = preorder.split(',')
    
    for node in nodes:
        slots -= 1  # We use one slot for the current node
        if slots < 0:  # If we run out of slots, it's invalid
            return False
        if node != '#':  # If it's a non-null node, we add two slots for children
            slots += 2
            
    return slots == 0  # In the end, we should have exactly zero slots
← Back to All Questions