• 欢迎光临~

Leetcode 199

开发技术 开发技术 2022-12-27 次浏览

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()]
程序员灯塔
转载请注明原文链接:Leetcode 199
喜欢 (0)