[331][中等][栈] 验证二叉树的前序序列化
题目描述
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #输入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
输出: true解题思路
最后更新于
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #输入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
输出: true最后更新于
输入: "1,#"
输出: false输入: "9,#,#,1"
输出: falseclass Solution:
def isValidSerialization(self, preorder: str) -> bool:
stack = []
num = 0
for c in preorder.split(','):
stack.append(c)
while len(stack) >= 3 and stack[-1] == '#' and stack[-2] == '#' and stack[-3] != '#':
stack.pop()
stack.pop()
stack.pop()
stack.append('#')
return len(stack) == 1 and stack[0] == '#'