题目:
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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
题意:
给定一棵二叉树,返回该二叉树层次遍历的结果
代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None :
return []
else :
result = []
father_node = [root]
father_val = [root.val]
result.append(father_val)
while len(father_node) > 0 :
child_node = []
child_val = []
for x in father_node :
if x.left != None :
child_node.append(x.left)
child_val.append(x.left.val)
if x.right != None :
child_node.append(x.right)
child_val.append(x.right.val)
father_node = child_node
if len(child_val) > 0 : #此处要引起重视,当father_node 中的节点的孩子都为空的时候(节点为叶节点时),child_node 及child_val 都是空的,此时,不能把空的child_val 插在result里面(child_val 为空的情况必然会出现一次,切记不能添加在result里)
result.append(child_val)
return result
笔记:
与前面寻找二叉搜索树中两个节点的最小祖先节点一样,Python实现层次遍历,可用两个临时list当做队列来实现
临时list存储当前父节点的所有孩子,遍历所有孩子之后,临时list赋给父节点list,继续遍历他们的孩子。