Concise 20 lines C++ solution


  • 1
    Z
    class Solution {
    public:
        bool isValidSerialization(string preorder) {
            int stackNums = 0;
            stringstream ss(preorder);
            string item;
            vector<string> treenodes;
            while(getline(ss,item,',')){
                treenodes.push_back(item);
            }
            int i=0;
            if(treenodes.size() %2 ==0) return false;
            while((i<treenodes.size()) && (treenodes[i]!="#" || stackNums!=0)){
                if(treenodes[i]!="#")
                    stackNums ++;
                else
                    stackNums--;
                i++;    
            }
            return (i == treenodes.size()-1)? true:false;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.