Verify Preorder Serialization of a Binary Tree

Updated on 03 July, 2025
Verify Preorder Serialization of a Binary Tree header image

Problem Statement

Serialization of a binary tree can be efficiently done using preorder traversal, wherein a non-null node is serialized by recording its value and a null node by using a sentinel, often represented as '#'. Provided with a string of comma-separated values denoted as preorder, which purportedly represents a serialized binary tree in preorder format, the task is to ascertain whether the string could represent a valid binary tree serialized in the preorder traversal methodology. Each item in this string is strictly an integer or the character '#'. The formulation guarantees that the input format eliminates a sequence of consecutive commas. The challenge is to compute the validity of the serialization without reconstructing the binary tree itself.

Examples

Example 1

Input:

preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"

Output:

true

Example 2

Input:

preorder = "1,#"

Output:

false

Example 3

Input:

preorder = "9,#,#,1"

Output:

false

Constraints

  • 1 <= preorder.length <= 104
  • preorder consist of integers in the range [0, 100] and '#' separated by commas ','.

Approach and Intuition

The validation of a serialized binary tree in preorder format revolves primarily around understanding the structure of binary trees and utilization of a stack to simulate the insertion of elements:

  1. Understanding Nodes and Null Indicators:

    • In a correctly serialized preorder traversal of a binary tree, every real node should have exactly two children, which could be either real nodes or null (represented as '#').
  2. Using a Stack or Counters:

    • We could use a stack or a simple counter to keep track of the requirements of leaf nodes or null indicators. Initially, we expect one root node node. As we process the input, whenever we encounter a node, it increases the expectations of two more child nodes (or nulls). A null node, on the other hand, resolves one expectation without creating new ones as it signifies the end of a branch.
  3. Step-by-Step Process:

    • Start by setting an expectation count to 1, expecting one root node.
    • As iterating over preorder:
      1. For each non-null node value, decrement the expectation by one (since it fulfills one expectation), and add two (setting expectation for its two children).
      2. For a null ('#'), merely decrement the expectation by one.
      3. If at any point, the expectation drops to zero before the end of the string, more nodes are in the string than required which violates the tree structure.
      4. Conversely, if there are expectations left unmet at the end of the string (non-zero value), it indicates missing nodes.
  4. Validation Point:

    • The sequence is valid if and only if, by the end of the preprocessing, the expectation is exactly zero, implying that every expected node or null placeholder was perfectly matched.

By habituating to this logical traversal and utilizing either a counter for node expectations or employing a stack mechanism, the serialized string can be validated against the standard principles of binary tree structure in a preorder traversal context.

Solutions

  • Java
java
class Solution {
  public boolean checkValidSerialization(String preorder) {
    int availableSlots = 1;
    int length = preorder.length();
    for(int index = 0; index < length; ++index) {
      if (preorder.charAt(index) == ',') {
        --availableSlots;
    
        if (availableSlots < 0) return false;
            
        if (preorder.charAt(index - 1) != '#') availableSlots += 2;
      }
    }
    
    availableSlots = (preorder.charAt(length - 1) == '#') ? availableSlots - 1 : availableSlots + 1;
    return availableSlots == 0;
  }
}

The provided Java program checks if the given preorder serialization of a binary tree is valid. Here's a breakdown of how the algorithm functions:

  • Initialize availableSlots to 1. This variable tracks the number of nodes that can be placed in the tree.
  • Loop through each character in the preorder string:
    • On encountering a comma, decrease availableSlots by 1 because the current node has consumed one slot.
    • If availableSlots becomes negative at any point after processing a comma, the serialization is immediately deemed invalid and the function returns false.
    • If the character before the comma is not a # (indicating it's a non-null node), increase availableSlots by 2. This is because a non-null node adds two more slots for its children.
  • After the loop, adjust availableSlots for the last node. If it's #, decrease by 1; if it's not, increase by 1.
  • The serialization is considered valid if, and only if, availableSlots equals 0 at the end of the sequence.

Keep the following key aspects in mind:

  • This logic effectively simulates the addition of nodes to an implicit binary tree, maintaining a count of how many more nodes are permissible for the tree to remain valid.
  • The key concept driving the validation is that a non-null node not only occupies a slot but also creates new slots for future child nodes.

This solution efficiently assesses the validity of the serialization with a single pass through the input string, maintaining a constant space usage relative to the input size.

Comments

No comments yet.