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 \ 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