leetcode 面试题32 (剑指offer)- II. 从上到下打印二叉树 II(python3)
程序员文章站
2022-07-15 19:48:44
...
面试题32 - II. 从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
# 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 []
res = [] #输出打印的结果
queue = [root]
while queue:
tem = []
for i in range(len(queue)): #表示循环多少次
node = queue.pop(0)
tem.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(tem)
return res