from collections import deque
from typing import List, Optional
from publicmatt.leet import TreeNode
def level_order(root: Optional[TreeNode]) -> List[List[int]]:
out = []
q = deque()
q.append(root)
while q:
size = len(q)
nodes = []
for i in range(size):
node = q.popleft()
if node:
nodes.append(node.val)
q.append(node.left)
q.append(node.right)
if nodes:
out.append(nodes)
return out