【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)
【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)
标签: LeetCode
题目地址:https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/description/
题目描述:
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
题目大意
给了一个先序遍历,判断能不能构成合法的二叉树。这个字符串中,#表示空节点。
解题方法
我们的思路应该是这样的:判断一个二叉树是否合法的情况,那么应该是个递归或者循环问题。那么解决问题的思路是从顶部向下分析还是从底下向顶部分析呢?正确的结果应该是从二叉树的底部向上进行分析,因为我们可以通过#号判断是否是空节点,然后判断最底下的叶子节点是否含有两个空孩子的方式,循环向上解决这个问题。
所以这个题的思路就很明了了:用一个栈,从字符串的左侧向右依次进栈,如果满足栈的后三位是数字,#,#的模式时,说明可以构成合法的叶子节点,把这个叶子节点换成#号,代表空节点,然后继续遍历。最后应该只剩下一个#,那么就是一个合法的二叉树。
如:”9,3,4,#,#,1,#,#,2,#,6,#,#” 遇到x # #的时候,就把它变为 #
模拟一遍过程:
9,3,4,#,# => 9,3,# 继续读
9,3,#,1,#,# => 9,3,#,# => 9,# 继续读
9,#2,#,6,#,# => 9,#,2,#,# => 9,#,# => #
class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
stack = []
for node in preorder.split(','):
stack.append(node)
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.pop() == '#'
方法二:
这个方法还是第一次使用:看出度和入度的差。
我们知道一个树(甚至图),所有节点的入度之和等于出度之和。那么可以根据这个条件进行有效性的判断。
对于二叉树,我们把空的地方也作为叶子节点(如题目中的#),那么有
- 所有的非空节点提供2个出度和1个入度(根除外)
- 所有的空节点但提供0个出度和1个入度
我们在遍历的时候,计算diff = outdegree – indegree. 当一个节点出现的时候,diff – 1,因为它提供一个入度;当节点不是#的时候,diff+2(提供两个出度) 如果序列式合法的,那么遍历过程中diff >=0 且最后结果为0.
这里解释一下为什么diff的初始化为1.因为,我们加入一个非空节点时,都会先减去一个入度,再加上两个出度。但是由于根节点没有父节点,所以其入度为0,出度为2.因此diff初始化为1,是为了再加入根节点的时候,先减去一个入度,再加上两个出度,正好应该是2.
class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
nodes = preorder.split(',')
diff = 1
for node in nodes:
diff -= 1
if diff < 0:
return False
if node != '#':
diff += 2
return diff == 0
参考:https://www.hrwhisper.me/leetcode-verify-preorder-serialization-of-a-binary-tree/
日期
2018 年 3 月 13 日
【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)的更多相关文章
- leetcode 331. Verify Preorder Serialization of a Binary Tree
传送门 331. Verify Preorder Serialization of a Binary Tree My Submissions QuestionEditorial Solution To ...
- 【LeetCode】Verify Preorder Serialization of a Binary Tree(331)
1. Description One way to serialize a binary tree is to use pre-order traversal. When we encounter a ...
- LeetCode OJ 331. Verify Preorder Serialization of a Binary Tree
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...
- [LeetCode] 331. Verify Preorder Serialization of a Binary Tree_Medium tag: stack
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...
- 【leetcode】331. Verify Preorder Serialization of a Binary Tree
题目如下: One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null ...
- 331. Verify Preorder Serialization of a Binary Tree
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...
- 331. Verify Preorder Serialization of a Binary Tree -- 判断是否为合法的先序序列
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...
- 331 Verify Preorder Serialization of a Binary Tree 验证二叉树的前序序列化
序列化二叉树的一种方法是使用前序遍历.当我们遇到一个非空节点时,我们可以记录这个节点的值.如果它是一个空节点,我们可以使用一个标记值,例如 #. _9_ / \ 3 2 ...
- LeetCode 331. 验证二叉树的前序序列化(Verify Preorder Serialization of a Binary Tree) 27
331. 验证二叉树的前序序列化 331. Verify Preorder Serialization of a Binary Tree 题目描述 每日一算法2019/5/30Day 27LeetCo ...
随机推荐
- exit(0) exit(1) return() 3个的区别
exit(0):正常运行程序并退出程序: exit(1):非正常运行导致退出程序: return():返回函数,若在主函数中,则会退出函数并返回一值. 详细说: 1. return返回函数值,是关键字 ...
- CSS上下左右居中对齐
上下左右居中对齐 display: inline/inline-block 将父元素(容器)设定 text-align: center: 即可左右置中. display: block 将元素本身的 ...
- vi查找替换命令详解 (转载)
转载至: http://blog.csdn.net/lanxinju/article/details/5731843 一.查找 查找命令 /pattern<Enter> :向下查找pa ...
- Does compiler create default constructor when we write our own?
In C++, compiler by default creates default constructor for every class. But, if we define our own c ...
- malloc() vs new
Following are the differences between malloc() and operator new. (1)new calls constructors, while ma ...
- 【Linux】【Shell】【Basic】Programming
shell脚本编程: 编程语言的分类:根据运行方式 编译运行:源代码-->编译器(编译)-->程序文件 解释运行:源代码-->运行时启动解释器,又解释器边解释边运行 根据其编程过程中 ...
- Python @函数装饰器及用法(超级详细)
函数装饰器的工作原理是怎样的呢?假设用 funA() 函数装饰器去装饰 funB() 函数,如下所示: #funA 作为装饰器函数 def funA(fn): #... fn() # 执行传入的fn参 ...
- Springboot 入门及Demo
一:SpringBoot入门1.1:SpringBoot简介Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的 ...
- Python pyecharts绘制饼图
一.pyecharts绘制饼图语法简介 饼图主要用于表现不同类目的数据在总和中的占比.每个的弧度不是数据量的占比pie.add()方法的用法add(name, attr, value, radius= ...
- time_formatter(uaf)
拿到题目先例行检查 然后进入主函数查看程序流程, 进入函数 这些字符串对我们选择1的输入进行了限制 在输入里面,可以看到strdup这个关键性的函数 调用了malloc这个函数 在选择四里面,可以看到 ...