102. 二叉树的层序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 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: Optional[TreeNode]) -> List[List[int]]:
result,result_sub,list_ = [],[],[]
if root: list_.append(root)
while list_:
size = len(list_)
# print(size)
while size:
root = list_.pop(0)
result_sub.append(root.val)
size -= 1
if root.left:
list_.append(root.left)
if root.right:
list_.append(root.right)
# print(list_)
result.append(result_sub)
result_sub = []
return result