C++ solution in 3ms


  • 0
    V
    class Solution {
    public:
        int __isValidSerialization(string & preorder, int start){
            int i = 0;
            while(preorder[start+i] == ',')i++;
            if (preorder[start+i] == '#')return start+i+1;
            
            while(preorder[start+i] !=',' && start+i < preorder.size()-1)i++;
            
            if (start+i >= preorder.size() -1) return -1;
            
            int leftend = __isValidSerialization(preorder, start + i);
            if (leftend == -1) return -1;
            
            int rightend = __isValidSerialization(preorder, leftend);
            if (rightend == -1) return -1;
            
            return rightend;
        }
        bool isValidSerialization(string preorder) {
           int ret = __isValidSerialization(preorder, 0);
           
           if (ret == preorder.size()) 
            return true;
            
           return false;
        }
    };
    

Log in to reply
 

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