您的位置:首页 > 编程语言 > Python开发

[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
{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
\
5
The 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