• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
鱼市口
博客园    首页    新随笔    联系   管理    订阅  订阅
Leetcode 199

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.

 

Analysis: given the depth, each depth we can only see the rightmost node(leaf) in exists. So actually the question is asking for a DFS for the rightmost nodes each stage.

So we can have a BFS, keep each level's rightmost node in a queue. Then output the nodes in the queue.

# 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]:
    d = {}
    def f(r,i):
      if r:
        d[i] = r.val
        f(r->right, i+1)
        f(r->left, i+1)
    
    f(root,0)
    return  d[*values()]
posted on 2022-12-27 23:20  鱼市口  阅读(23)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3