```
class Solution {
public:
bool isValidSerialization(string preorder) {
int n=preorder.size();
int num=0,ctr=0;
for(int i=0;i<n;i++){
if(preorder[i]=='#') ctr++;
else if(preorder[i]!=','){
num++;
while(i+1<n&&preorder[i+1]>='0'&&preorder[i+1]<='9') i++;
}
if(ctr==num+1&&i<n-1) return false;
}
if(ctr==num+1) return true;
else return false;
}
```

};