给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
方法:
首先还是按照之前的文章对于深度广度分析,采用列表进行实现层序遍历,即广度搜索。但是这道题特别要注意的一点是,输出的形式不是单纯的广度搜索。题目要求每一层在一个子列表中,那么在大循环中还需要增加一个小循环,在实现广度搜索时,实际上是以列表形式对当前节点进行储存的。因此每一层的节点实际上就会放在一个子列表中,因此每一层中的节点个数实际就是此列表的长度。那么,在增加一个循环即可实现。
最终的AC解为:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
result = []
temp = [root]
while len(temp):
con = []
for _ in range(len(temp)):
num = temp.pop(0)
if num:
con.append(num.val)
if num.left:
temp.append(num.left)
if num.right:
temp.append(num.right)
result.append(con)
return result