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