LeetCode – Verify Preorder Serialization of a Binary Tree (Java)

One way to serialize a binary tree is to use pre-order 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 #.

    /   \
   3     2
  / \   / \
 4   1  #  6
/ \ / \   / \
# # # #   # #

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, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Java Solution - Stack

We can keep removing the leaf node until there is no one to remove. If a sequence is like "4 # #", change it to "#" and continue. We need a stack so that we can record previous removed nodes.

Here is an example:

public boolean isValidSerialization(String preorder) {
    LinkedList<String> stack = new LinkedList<String>();
    String[] arr = preorder.split(",");
    for(int i=0; i<arr.length; i++){
            && stack.get(stack.size()-1).equals("#")
            && stack.get(stack.size()-2).equals("#")
            && !stack.get(stack.size()-3).equals("#")){
    if(stack.size()==1 && stack.get(0).equals("#"))
        return true;
        return false;
Category >> Others  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Nada Abo ElSeod

    The code above won’t work in case of “A, B, #, #, #” which is a valid serialization of a root node A with a left child B.

  • navin

    code is incorrect:
    breaks for the case 9,3,4,#,2,#,#,1,#,#,6,8,#,#,#

  • Rohit

    code is wrong

    93###.stops here

  • Iram22

    private static boolean verify(String s){
    String arr[]=s.split(",");
    Stack stack=new Stack();
    if(arr.length==0 || arr[0]=="#") return true;
    for(int i=1;i<arr.length;i++){
    if(stack.size()==0) return false;
    if(i!=stack.peek()+1){ stack.pop();}
    if(arr[i].equals("#")){ continue;}
    if(stack.size()!=0) return false;
    return true;

  • Matias SM

    Alternate solution:

    boolean isValidPreorder(String serialization) {
    String[] nodes = serialization.split(",");
    return isValidPreorder(nodes, 0) == nodes.length;

    int isValidPreorder(String[] nodes, int startIdx) {
    if (startIdx >= nodes.length) return -1;

    //end node
    if (nodes[startIdx].equals("#")) return startIdx + 1;

    //left branch
    int nextIdx = isValidPreorder(nodes, startIdx + 1);

    //right branch (note that it must exists to be a valid in order)
    return nextIdx != -1? isValidPreorder(nodes, nextIdx) : -1;

    Disclaimer: I don’t think I’m breaking the condition of “not reconstruct the tree” since I’m not doing it per-se.

  • Sonam Gupta

    this code is wrong.