Leetcode [从上到下打印二叉树 II]
牛客 [把二叉树打印成多行]
配合
(python版)《剑指Offer》JZ22:从上往下打印二叉树
食用更佳
比一代版本 只多了个 当前层的循环
# 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 not root:
return []
queue = [root]
res = []
while queue:
tmp = [] # 存储单层的结果
for _ in range(len(queue)):
node = queue.pop(0) # 队首元素
tmp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(tmp)
return res
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/solution/mian-shi-ti-32-ii-cong-shang-dao-xia-da-yin-er-c-5/