Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Verify Preorder Serialization of a Binary Tree problem solution

YASH PAL, 31 July 2024

In this Leetcode Verify Preorder Serialization of a Binary Tree problem solution, One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node’s value. If it is a null node, we record using a sentinel value such as ‘#’. For example, the above binary tree can be serialized to the string “9,3,4,#,#,1,#,#,2,#,6,#,#”, where ‘#’ represents a null node.

Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character ‘#’ representing null pointer.

Leetcode Verify Preorder Serialization of a Binary Tree problem solution

Problem solution in Python.

class Solution:
    def isValidSerialization(self, preorder: str) -> bool:
        preorderList = preorder.split(',')
        if len(preorderList)%2 != 1:
            return False
        stack = []
        for node in preorderList:
            stack.append(node)
            while len(stack) >= 3 and stack[-2] == stack[-1] == '#' and stack[-3] != '#':
                for i in range(3):
                    stack.pop()
                stack.append('#')
        return len(stack) == 1 and stack[0] == '#'

Problem solution in Java.

public boolean isValidSerialization(String preorder) {

    if(preorder.length()==1 && preorder.charAt(0)=='#'){
        return true;
    }
    
    Deque<Boolean> stackObj = new ArrayDeque<Boolean>();
    
   String[] nodes= preorder.split(",");
    
    for(int i=0;i<nodes.length;i++){
        
        if(nodes[i].equals("#")){
            
            if(stackObj.isEmpty()){
                return false;
            }else{
                
               while(!stackObj.isEmpty() && stackObj.getFirst()){
                stackObj.removeFirst();
               }
                
                if(!stackObj.isEmpty()){
                    stackObj.removeFirst();
                    stackObj.addFirst(true);
                }else if(i+1<nodes.length){
                    return false;
                }
            }
        }else{
            stackObj.addFirst(false);
        }
    }
    
    if(stackObj.isEmpty()){
        return true;
    }
    
    return false;[]
}

Problem solution in C++.

class Solution {
public:
    bool isValidSerialization(string preorder) {
        int internalNode = 0, externalNode = 0;
        char inString[preorder.length() + 1];
        strcpy(inString, preorder.c_str());
        char *nodeValue = strtok(inString, ",");
        while (nodeValue) {
            if (nodeValue[0] == '#') ++externalNode;
            else ++internalNode;
            nodeValue = strtok(NULL, ",");
            if (externalNode == internalNode + 1) {
                if (nodeValue) return false;
                return true;
            }
        }
        return false;
    }
};

Problem solution in C.

char *checkTree(char *start) {
    if (*start == 0) return 0;
    if (*start == '#') return start + 1;
    char *next = start + 1;
    next = checkTree(next);
    if (next == 0) return 0;
    next = checkTree(next);
    if (next == 0) return 0;
    return next;
}

bool isValidSerialization(char * preorder){
    char *c; int i;
    for (c = preorder, i = 0; *c; c++) {
        if (*c == ',') { i++; continue; }
        if (*c != '#') { preorder[i] = 'X'; continue; }
        preorder[i] = '#';
    }
    preorder[i+1] = 0;

    char *end = checkTree(preorder);
    if (end == 0) return false;
    if (*end != 0) return false;
    return true;
}

coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
How to download udemy paid courses for free

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
©2025 Programming101 | WordPress Theme by SuperbThemes