Leetcode-199.二叉树的右视图(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
from collections import deque
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        res=[]
        if not root:
            return res
        queue=deque([root])
        while queue:
            level_size=len(queue)
            for i in range(level_size):
                current_node=queue.popleft()
                if i==level_size-1:
                    res.append(current_node.val)
                if current_node.left:
                    queue.append(current_node.left)
                if current_node.right:
                    queue.append(current_node.right)
        return res

你可能感兴趣的:(leetcode,leetcode,算法,python)