网站开发的公司属于什么行业百度总部公司地址在哪里
描述
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
思路
- 对树进行深度优先搜索,在搜索过程中,我们总是先访问右子树。那么对于每一层来说,我们在这层见到的第一个结点一定是最右边的结点
- 但凡循环or遍历都会有中间状态产生,如奇偶、遍历的计数、嵌套遍历的话内层循环就会有首位值,这些都将是重要信号,可以暂存利用
# 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]:depth_mapping_rightmost_value = dict() # 深度为索引,存放节点的值max_depth = -1queue = deque([(root, 0)])while queue:node, depth = queue.popleft()if node is not None:# 维护二叉树的最大深度max_depth = max(max_depth, depth)""" 如果每层存放节点都是从左往右,那么每一层最后一个访问到的节点值是每层最右端节点,因此不断更新对应深度的信息即可"""depth_mapping_rightmost_value[depth] = node.valqueue.append((node.left, depth + 1))queue.append((node.right, depth + 1))return [depth_mapping_rightmost_value[depth] for depth in range(max_depth + 1)]