ZhongKuo0228 / study

0 stars 0 forks source link

199. Binary Tree Right Side View #96

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago

用 BFS 把每層最右邊抓出來即可

# 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]:
        queue, rightmost_nodes = [], []
        if not root:
            return queue
        queue.append(root)
        while queue:
            cur_len = len(queue)
            rightmost_nodes.append(queue[-1].val)
            for _ in range(cur_len):
                root = queue[0]
                queue.pop(0)
                if root.left:
                    queue.append(root.left)
                if root.right:
                    queue.append(root.right)
        return rightmost_nodes