您的位置:首页 > 其它

leetcode 之 Verify Preorder Serialization of a Binary Tree

2016-06-06 16:52 417 查看
题目描述:

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as
#
.

_9_
/   \
3     2
/ \   / \
4   1  #  6
/ \ / \   / \
# # # #   # #

For example, the above binary tree can be serialized to the string
"9,3,4,#,#,1,#,#,2,#,6,#,#"
, where
#
represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character
'#'
representing
null
pointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as
"1,,3"
.

Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"

Return
true


Example 2:
"1,#"

Return
false


Example 3:
"9,#,#,1"

Return
false


即 给定一颗二叉树的前序遍历串,判断这个串是不是合法的。

分析:1. 前序遍历的即为 根左右遍历,首先访问根节点,然后依次左子树和右子树。

   2. 对于9,3,4,#,#,1,#,#,2,#,6,#,# 这个串来说,6, #,# 一定是一个叶子节点,将其移除后,替换为"#"

   3. 这时串变为: 9,3,4,#,#,1,#,#,2,#,#,继续第二步操作

使用堆栈保存输入的串,当堆栈后三个元素为 x## 时, 移除这三个元素,并加入#, 最后如果堆栈长度为1 且 值为# ,则返回true

代码如下:

class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
l = len(preorder)
if l == 1 and preorder[0] == "#":
return True
if preorder[0] == "#":
return False
ls = preorder.split(",")
stack = []
for i in ls:
stack.append(i)
while len(stack) >= 3 and stack[-2] == "#" and stack[-1] == "#" and stack[-3] != "#":
stack.pop()
stack.pop()
stack.pop()
stack.append("#")

return len(stack) == 1 and stack[0] == "#"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: