1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: bool isValidSerialization(string preorder) { int n = preorder.size(), i = 0, slots = 1; while (i < n) { if (slots == 0) return false; if (preorder[i] == ',') { ++i; } else if (preorder[i] == '#') { --slots; ++i; } else { while (i < n && preorder[i] != ',') ++i; ++slots; } } return slots == 0; } };
|