My C++ recursive solution && non-recursive soluton
Just do recursion. helper here is to check if we can use the characters of preorder starting from cur to build a valid tree (doesn't have to use all the charact
Just do recursion. helper here is to check if we can use the characters of preorder starting from cur to build a valid tree (doesn't have to use all the characters). So, if\n1) the current value is '#', then return true;\n2) if the current value is not '#", we have to check if we can use the rest characters to build two valid subtrees\n\nAt last, even we can build a valid tree with preorder, we have to check if we use all the characters, if not, still return false;\n\n    class Solution {\n    private:\n        bool helper(string &preorder, int &cur, int len)\n        {\n            if(cur>=len) return false; // if we reach the end of preorder while we need a new node, return false\n            while(cur<len && preorder[cur]!=',') ++cur; // get the value of the current node, which ends at ','\n            if(preorder[++cur-2]=='#') return true; // if the current node is null, then return true, and move cur forward to skip ','\n            if(helper(preorder, cur, len) && helper(preorder, cur, len)) return true; // check if the left subtree and the right subree has valid serialization, if so, return true\n            else return false;\n        }\n    public:\n        bool isValidSerialization(string preorder) {\n            int len = preorder.size(), cur=0;\n            if(len && helper(preorder, cur, len) && cur>len) return true; // we need to check cur>len to make sure all characters are used\n            return false;\n        }\n    };\n\nFor non-recursive solution, use numTrees to track how many subtrees we need to construct. If the current node value is '#', then it is an empty tree, so reduce numTrees by 1, otherwise, it is a non-null node, increase numTrees by 1. Quit the outer while loop when either we reach the end of preorder or there is no subtrees to be constructed. Return true only when we use all the characters of preorder to build all the required subtrees.\n\n    class Solution {\n    public:\n        bool isValidSerialization(string preorder) {\n            int numTrees  = 1, cur=0, len=preorder.size();\n            while(cur<len && numTrees>0)\n            {\n                while(cur<len && preorder[cur]!=',') ++cur;\n                if(preorder[++cur-2]=='#') --numTrees;\n                else ++numTrees;\n            }\n            return cur>len && numTrees<=0;\n        }\n    };
[]