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";
  • 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.