최대 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        answer = []
        
        if not root:
            return answer
        q: deque = collections.deque()
        q.append(root)
        
        while q:
            size = len(q)
            temps = []
            for i in range(size):
                node = q.popleft()
                temps.append(node.val)
                if node.left:
                    q.append(node.left)
                    
                if node.right:
                    q.append(node.right)
        
            answer.append(temps[-1])
        
        return answer

댓글남기기