class Solution {
public:
bool isValidSerialization(string preorder) {
istringstream iss(preorder);
vector<string> arr;
string s;
int cnt = 0;
while (getline(iss, s, ',')) arr.push_back(s);
for (int i = 0; i < arr.size() - 1; ++i) {
if (arr[i] == "#") {
if (cnt == 0) return false;
cnt--;
} else {
cnt++;
}
}
return cnt == 0 && arr.back() == "#";
}
};
class Solution {
public:
bool isValidSerialization(string pre) {
int cnt = 1;
pre += ",";
for (int i = 0; i < pre.size(); ++i) {
if (pre[i] != ',') continue;
if (--cnt < 0) return false;
if (pre[i - 1] != '#') cnt += 2;
}
return cnt == 0;
}
};