leetcode 从上到下打印二叉树 III 代码分享
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = deque([root])
res = []
reverse = False
while queue:
size = len(queue)
part = []
while size > 0:
size -= 1
tree = queue.popleft()
part.append(tree.val)
children = [tree.left, tree.right]
if any(children):
for child in children:
if child:
queue.append(child)
if reverse:
res.append(part[::-1])
else:
res.append(part)
reverse = not reverse
return res