# 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):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        level1,level2,nums,ans=deque(),deque(),[],[]
        level1.append(root)
        while level1 or level2:
            while level1:
                temp=level1[0]
                nums.append(temp.val)
                level1.popleft()
                if temp.left:
                    level2.append(temp.left)
                if temp.right:
                    level2.append(temp.right)
            ans.append(nums.copy())
            level1=level2.copy()
            level2.clear()
            nums.clear()
        return ans