199. Binary Tree Right Side View

Given theĀ rootĀ of a binary tree, imagine yourself standing on theĀ right sideĀ of it, returnĀ the values of the nodes you can see ordered from top to bottom.

class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        
        ans = [root.val]
        
        q = deque([root])
        
        while q:
            level_len = len(q)
            
            for _ in range(level_len):
                cur = q.popleft()
                if cur.left: q.append(cur.left)
                if cur.right: q.append(cur.right)
            if q:
                ans.append(q[-1].val)
        return ans

Categories:: tree, binary-tree, bfs