331. Verify Preorder Serialization of a Binary Tree

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;
    }
}

Last updated