Simple Regex Solution in JavaScript


  • 0
    Y
    var isValidSerialization = function(preorder) {
        var oldTree = "",
            newTree = preorder;
            
        while (oldTree !== newTree) {
            oldTree = newTree;
            newTree = oldTree.replace(/\d+,#,#/g, "#")
        }
        
        if (newTree === "#")
            return true;
        else
            return false;
    };
    

    Keep replacing the leaf representation, i.e. "num,#,#", with # until the string doesn't change. Then check if the final string is the same as "#".


Log in to reply
 

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