Simple C++ in 4ms with comments
class Solution {\n    public:\n        bool isValidSerialization(string preorder) {\n            if (preorder.empty()) return true;\n    \n            int expec
    class Solution {\n    public:\n        bool isValidSerialization(string preorder) {\n            if (preorder.empty()) return true;\n    \n            int expected_chars = 1;  // root\n            int next_expected_chars = 0;\n    \n            stringstream ss(preorder);\n            string item;\n            while (getline(ss, item, ',')) {\n                if (expected_chars == 0) return false;  // we did not expect any more chars\n                if (item != "#") next_expected_chars += 2;  // any non-null node will require 2 children in the next level\n                if (--expected_chars == 0) {  // end of level\n                    expected_chars = next_expected_chars;\n                    next_expected_chars = 0;\n                }\n            }\n    \n            // Were we expecting any more chars?\n            return expected_chars == 0;\n        }\n    };
[]