[LeetCode] Binary Tree Level Order Traversal
2015-11-01 00:00
609 查看
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree
return its level order traversal as:
confused what
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
这题目其实是要求按层遍历二叉树,并且分层输出。在遍历二叉树时最简单就是递归了,但简单递归无法保存层的信息,在借助队列遍历时,也只能简单的按层输出,无法确
元素在那一层,这里借鉴了别人的思想:设置两个标记量分别标记parent数和child数,再说一次,要得到按层遍历的序列不难,难的是怎么确定什么时候是分层,开始的
时候queue只有root一个元素,此时parentIndex = 1, childIndex = 0,由于它的left和right都为飞空,所以root.left 和 root.right 分别入队列,
childIndex 递增两次,即childIndex += 2。。。算了,我也说不清,还是上代码吧:
版权声明:本文为博主原创文章,未经博主允许不得转载。
For example:
Given binary tree
{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what
"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
这题目其实是要求按层遍历二叉树,并且分层输出。在遍历二叉树时最简单就是递归了,但简单递归无法保存层的信息,在借助队列遍历时,也只能简单的按层输出,无法确
元素在那一层,这里借鉴了别人的思想:设置两个标记量分别标记parent数和child数,再说一次,要得到按层遍历的序列不难,难的是怎么确定什么时候是分层,开始的
时候queue只有root一个元素,此时parentIndex = 1, childIndex = 0,由于它的left和right都为飞空,所以root.left 和 root.right 分别入队列,
childIndex 递增两次,即childIndex += 2。。。算了,我也说不清,还是上代码吧:
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @param sum, an integer # @return a boolean def levelOrder(self, root): if None == root: return [] queue = [root] ret = [] tmp = [] parentIndex = 1 childIndex = 0 while len(queue) > 0: leaf = queue[0] tmp.append(leaf.val) del queue[0] if None != leaf.left: queue.append(leaf.left) childIndex += 1 if None != leaf.right: queue.append(leaf.right) childIndex += 1 parentIndex -= 1 if 0 == parentIndex: ret.append(tmp) tmp = [] parentIndex = childIndex childIndex = 0 return ret
版权声明:本文为博主原创文章,未经博主允许不得转载。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- AVL树-自平衡二叉查找树(Java实现)
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例