4ms C++ solution without using stack


  • 3
    G
    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;
    }
    

    };


  • 0
    S

    The name of the variable should be defined more readable, like num -> nodes, ctr ->leaf, etc. It's just based on leave should be node + 1.


  • 0
    G

    Thanks for your suggestion!


Log in to reply
 

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