최대 1 분 소요

Python

# 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]]:
        answer = []
        if root is None:
            return answer
        q: deque = collections.deque()
        q.append(root)
        while(len(q) > 0):
            temps = []
            node_size = len(q)
            while node_size > 0:
                node = q.popleft()
                temps.append(node.val)
                node_size -= 1
                if node.left is not None:
                    q.append(node.left)
                if node.right is not None:
                    q.append(node.right)
            answer.append(temps)
            
        return answer

댓글남기기