Leetcode-199.二叉树的右视图(Python)

2024-01-01 19:39:44

题目链接

需复习树的广度和深度遍历~

# 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

文章来源:https://blog.csdn.net/m0_53678795/article/details/135327615
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。