Verify Preorder Serialization of a Binary Tree
class Solution {
public:
    int nodes = 0, nulls = 0;
    int fun(vector<int> &s, int i)
    {
        if(i>=s.size()) return 10000;
        if(s[i]==-1) 
        {
            nulls++;
            return i;
        } 
        nodes++;
        int left = fun(s, i+1);
        int right = fun(s, left+1);
        return right;
    }
	
	
    bool isValidSerialization(string s) {
        vector<int>arr;
        string t;
		/////////String to Array conversion//////////
        for(auto i:s)
        {
            if(i=='#') arr.push_back(-1);
            else if(i==',') 
            {
                int n = 0;
                if(t.size())
                {
                    for(auto j:t) n = n*10 + j-'0';
                    arr.push_back(n);
                    t = "";
                }
            }
            else t += i;
        }
        if(t.size()) 
        {
            int n = 0;
            for(auto j:t) n = n*10 + j-'0';
            arr.push_back(n);
        }
		//////////////////////////////////////////////
		
		///////////////First Invalidity Check////////////////
        if(fun(arr, 0)==10000) return false;
		
		//////////////Check for Nodes and Nulls//////////////////
        for(auto i:arr) 
		{
            if(i==-1) nulls--;  ///Comparing with the Nodes and Nulls count in given preorder sequence
            else nodes--;
		}
        return (nodes==0 && nulls==0);
    }
};
Comments (0)