# 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
用 BFS 把每層最右邊抓出來即可