> For the complete documentation index, see [llms.txt](https://ucan.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ucan.gitbook.io/notes/stack/331.-verify-preorder-serialization-of-a-binary-tree.md).

# 331. Verify Preorder Serialization of a Binary Tree

```java
class Solution {
    public boolean isValidSerialization(String preorder) {
        // with null nodes, the binary tree can be considered as a full binary tree
        // full binary tree: every no-leaf node has two children
        // full binary tree: num(non-leaf)+1==num(leaf);
        // observation: cannot add more node to existing binary tree with all leaves are null
        
        int leaves =0, nonLeaves=0, i=0;
        String[] nodes = preorder.split(",");
        for(; i<nodes.length && nonLeaves+1 > leaves; i++){
            if(nodes[i].equals("#")) leaves++;
            else nonLeaves++;
        }
        
        return nonLeaves+1==leaves && nodes.length==i;
    }
}
```
