Yes a typical stack based problem. Please take care of corner cases.
class Solution { public: bool isValidSerialization(string preorder) { // Get tokens. vector<string> tokens; // true - is num; false - is null int i = 0; string tk; while(i < preorder.length()) { char c = preorder[i]; if(c == ',') { tokens.push_back(tk); tk.clear(); } else { tk += c; } i ++; } tokens.push_back(tk); int n = tokens.size(); if(n==1) return tokens[0] == "#"; if (n < 3) return false; // Go typedef pair<string, bool> Rec; // value - is on right i = 0; stack<Rec> stk; if(tokens[0] != "#") stk.push(Rec(tokens[i++], false)); while(!stk.empty() && (i < n)) { string tk = tokens[i++]; if(tk == "#") // '#' { if(!stk.top().second) // switch to right { stk.top().second = true; } else { while(!stk.empty() && stk.top().second) stk.pop(); if(!stk.empty()) stk.top().second = true; } } else { stk.push(Rec(tk, false)); } } return stk.empty() && (i == n); } };