鱼儿慢慢游~~

导航

 

题目描述:

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

代码如下:

 1 class Solution(object):
 2     def isValidSerialization(self, preorder):
 3         """
 4         :type preorder: str
 5         :rtype: bool
 6         """
 7         l = len(preorder)
 8         if l == 1 and preorder[0] == "#":
 9             return True
10         if preorder[0] == "#":
11             return False
12         ls = preorder.split(",")
13         stack = []
14         for i in ls:
15             stack.append(i)
16             while len(stack) >= 3 and stack[-2] == "#" and stack[-1] == "#" and stack[-3] != "#":
17                 stack.pop()
18                 stack.pop()
19                 stack.pop()
20                 stack.append("#")
21                 
22         return len(stack) == 1 and stack[0] == "#"

 

posted on 2016-06-06 16:52  miss_UU  阅读(166)  评论(0编辑  收藏  举报