[Python] simple stack, explained - LeetCode Discuss

PHOTO EMBED

Wed Mar 16 2022 13:38:38 GMT+0000 (Coordinated Universal Time)

Saved by @hisox85289

class Solution:
    def isValidSerialization(self, preorder):
        stack = []
        for elem in preorder.split(","):
            stack.append(elem)
            while len(stack) > 2 and stack[-2:] == ["#"]*2 and stack[-3] != "#":
                stack.pop(-3)
                stack.pop(-2)
            
        return stack == ["#"]
content_copyCOPY

https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1427004/Python-simple-stack-explained