Python straight forward with stack


  • 0
    D
    class Solution(object):
        def isValidSerialization(self, preorder):
            """
            :type preorder: str
            :rtype: bool
            """
            stack = []
            for char in preorder.split(','):
                stack.append(char)
                while len(stack) >= 3 and stack[-1] == stack[-2] == '#' and stack[-3] != '#':
                    stack.pop()
                    stack.pop()
                    stack.pop()
                    stack.append('#')
            return len(stack) == 1 and stack[0] == '#'
    

Log in to reply
 

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