二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如: 给定二叉树: [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
# 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: TreeNode) -> List[List[int]]: if root == None: return [] layer = [root] res = [] while len(layer): this_res = [] next_l = [] for n in layer: this_res.append(n.val) if n.left: next_l.append(n.left) if n.right: next_l.append(n.right) res.append(this_res) layer = next_l return res