# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: deflevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ifnot root: return [] queue, cur_level_ans,ans = [root], [], [] while queue: tmp = [] for node in queue: if node.left: tmp.append(node.left) if node.right: tmp.append(node.right) cur_level_ans.append(node.val) queue = tmp ans.append(cur_level_ans) cur_level_ans = [] return ans