My clear solution


  • 0
    A
    class Solution {
    public:
        bool isValidSerialization(string preorder) {
            stringstream ss(preorder);
            string token;
            
            if(!std::getline(ss, token, ',')) return false;
            
            int cnt = 0;
            if(token != "#") cnt++;
            
            while (cnt>0) {
                if (!std::getline(ss, token, ',')) break;
                if(token!="#") cnt++;
                if (!std::getline(ss, token, ',')) break;       
                if(token!="#") cnt++;            
                cnt--;
            }
        
            return cnt==0 && ss.eof();
        }
    };

Log in to reply
 

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