Simple Python solution using stack. With Explanation.
This is very simple problem if you use stacks. The key here is, when you see two consecutive "#" characters on stack, pop both of them and replace the topmost e
This is very simple problem if you use stacks. The key here is, when you see two consecutive "#" characters on stack, pop both of them and replace the topmost element on the stack with "#". Think of this step as collapsing (or folding) leaves into their parent node. When you fold leaves into the parent node, parent node becomes the leaf node. If you keep doing this for a valid input you should be able to fold all nodes into the root node until there is just one leaf node left.\n\nHere is an example,\n\n```\nPre-order traversal: [1,2,3,#,#,#,#]\nTree looks like:\n      1\n\t / \\\n    2   #\n   /  \\\n  3    #\n / \\\n#   #\n```\n\npreorder = 1,2,3,#,#,#,#\n\nPass 1:  stack = [1]\n\nPass 2: stack = [1,2]\n\nPass 3: stack = [1,2,3]\n\nPass 4: stack = [1,2,3,#]\n\nPass 5: stack = [1,2,3,#,#] -> two #s on top so pop them and replace top with #. -> stack = [1,2,#] i.e. we collapse 3\'s leaves:\n```\n      1\n\t / \\\n    2   #\n   /  \\\n  #    #\n```\n\nPass 6: stack = [1,2,#,#] -> two #s on top so pop them and replace top with #. -> stack = [1,#] i.e. we collapse 2\'s leaves:\n```\n      1\n\t / \\\n    #   #\n```\n\nPass 7: stack = [1,#,#] -> two #s on top so pop them and replace top with #. -> stack = [#] i.e. we collapse 1\'s leaves:\n```\n      #\n```\n\nIf there is only one # on stack at the end of the string then return True else return False.\n\nHere is the code for that,\n\n    class Solution(object):\n    def isValidSerialization(self, preorder):\n        """\n        :type preorder: str\n        :rtype: bool\n        """\n        stack = []\n        top = -1\n        preorder = preorder.split(\',\')\n        for s in preorder:\n            stack.append(s)\n            top += 1\n            while(self.endsWithTwoHashes(stack,top)):\n                h = stack.pop()\n                top -= 1\n                h = stack.pop()\n                top -= 1\n                if top < 0:\n                    return False\n                h = stack.pop()\n                stack.append(\'#\')\n            #print stack\n        if len(stack) == 1:\n            if stack[0] == \'#\':\n                return True\n        return False\n    \n    def endsWithTwoHashes(self,stack,top):\n        if top<1:\n            return False\n        if stack[top]==\'#\' and stack[top-1]==\'#\':\n            return True\n        return False
['Stack', 'Python']