就是BFS,同时把每层的值作为列表保存
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: result = list() layer = list() layer_val = list() size = 0 if not root: return [] layer_val.append(root.val) result.append(layer_val) layer.append(root) while layer: size = len(layer) layer_val = list() while size > 0: temp = layer[0] if temp.left: layer.append(temp.left) layer_val.append(temp.left.val) if temp.right: layer.append(temp.right) layer_val.append(temp.right.val) size -= 1 del layer[0] if layer_val == []: return result result.append(layer_val) return result