C++ 4ms solution, O(1) space, O(n) time
The capacity is the number of node that can be put in the tree. The initial value is 1, which means there can be a root.\n\nWhen adding a node, capacity--;\n\nW
The capacity is the number of node that can be put in the tree. The initial value is 1, which means there can be a root.\n\nWhen adding a node, capacity--;\n\nWhen adding  a non-NULL node, it means we obtains two more leafs, then capacity +=2.\n\nThe final capacity should be equal to 0\n\n\n    class Solution {\n    public:\n    bool isValidSerialization(string preorder) {\n        if (preorder.empty()) return false;\n        preorder+=',';\n        int sz=preorder.size(),idx=0;\n        int capacity=1;\n        for (idx=0;idx<sz;idx++){\n            if (preorder[idx]!=',') continue;\n            capacity--;\n            if (capacity<0) return false;\n            if (preorder[idx-1]!='#') capacity+=2;\n        }\n        return capacity==0;\n    }\n    };
[]