KatInterview

331. Verify Preorder Serialization of a Binary Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if a given comma-separated string is a valid preorder serialization of a binary tree. In this specific serialization format, non-null nodes are represented by their integer values, and null children are represented by a special sentinel character '#'. The core challenge is to verify if the sequence of numbers and '#' symbols adheres to the structural rules of a binary tree without actually reconstructing the tree.

Solution

Verify Preorder Serialization of a Binary Tree in Python

class Solution:
    def isValidSerialization(self, preorder: str) -> bool:
        # Split the preorder string into a list of nodes
        nodes = preorder.split(',')
        
        # 'slots' represents the number of available open slots for nodes.
        # A non-null node consumes 1 slot and provides 2.
        # A null node '#' consumes 1 slot and provides 0.
        slots = 1 # Start with a single slot for the root of the tree
        
        for node in nodes:
            # Each node, whether null or not, consumes one slot.
            slots -= 1
            
            # If slots become negative, it means we have a node but no place to attach it.
            # This indicates an invalid tree structure.
            if slots < 0:
                return False
            
            # A non-null node provides two new slots for its children.
            if node != '#':
                slots += 2
        
        # At the end, a valid serialization must leave us with exactly 0 slots.
        return slots == 0

Verify Preorder Serialization of a Binary Tree in Java

class Solution {
    public boolean isValidSerialization(String preorder) {
        // Split the string into nodes
        String[] nodes = preorder.split(",");
        
        // Represents the number of available slots for children
        int slots = 1; // Start with one slot for the root

        for (String node : nodes) {
            // Consume one slot for the current node
            slots--;

            // If there are no available slots to place the current node, it's invalid.
            // This happens if we have more nodes than the tree structure allows.
            if (slots < 0) {
                return false;
            }

            // A non-null node provides two new slots for its children.
            if (!node.equals("#")) {
                slots += 2;
            }
        }

        // A valid serialization must consume all available slots exactly.
        return slots == 0;
    }
}

Verify Preorder Serialization of a Binary Tree in C++

class Solution {
public:
    bool isValidSerialization(string preorder) {
        std::stringstream ss(preorder);
        std::string token;
        int slots = 1; // Start with one slot for the root

        while (getline(ss, token, ',')) {
            // Consume one slot for the current node.
            slots--;

            // If we run out of slots before processing all nodes, it's invalid.
            // This means a node is trying to be placed without a parent.
            if (slots < 0) {
                return false;
            }

            // If the node is not null, it provides two new slots for its children.
            if (token != "#") {
                slots += 2;
            }
        }

        // At the end, all slots must be filled. A valid serialization uses up all slots.
        return slots == 0;
    }
};

Verify Preorder Serialization of a Binary Tree in TypeScript

function isValidSerialization(preorder: string): boolean {
    const nodes = preorder.split(',');
    
    // 'slots' tracks the number of available positions for child nodes.
    let slots = 1; // We start with one slot available for the root.

    for (const node of nodes) {
        // Each node consumes one available slot.
        slots--;

        // If slots drop below zero, it means we are trying to place a node
        // where no parent slot is available, which is invalid.
        if (slots < 0) {
            return false;
        }

        // A non-null node is a parent itself, so it provides two new slots
        // for its left and right children.
        if (node !== '#') {
            slots += 2;
        }
    }

    // For a serialization to be valid, all available slots must be precisely
    // filled by the end of the traversal. So, slots must be 0.
    return slots === 0;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.