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

本文介绍了一种二叉树的层次遍历方法,并详细解释了如何通过队列实现节点值的分层输出。该算法利用父节点和子节点数量标记来确定遍历的层级。
1547

被折叠的 条评论
为什么被折叠?



