从零开始刷LeetCode----二叉树的右视图

题目:

  给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
   1             <---
 /   \
2     3         <---
 \     \
  5     4       <---

来源:力扣(LeetCode)

方法一:广度优先搜索

  首先,想到最简单的办法就是把二叉树层次遍历的代码拿过来,并且是遍历顺序有从左到右,这样把遍历出来的二叉树的每一层的最后一个数值就是其左视图。

 1 from collections import deque
 2 
 3 class Solution(object):
 4     def rightSideView(self, root):
 5         rightmost_value_at_depth = dict() # 深度为索引,存放节点的值
 6         max_depth = -1
 7 
 8         queue = deque([(root, 0)])
 9         while queue:
10             node, depth = queue.popleft()
11 
12             if node is not None:
13                 # 维护二叉树的最大深度
14                 max_depth = max(max_depth, depth)
15 
16                 # 由于每一层最后一个访问到的节点才是我们要的答案,因此不断更新对应深度的信息即可
17                 rightmost_value_at_depth[depth] = node.val
18 
19                 queue.append((node.left, depth+1))
20                 queue.append((node.right, depth+1))
21 
22         return [rightmost_value_at_depth[depth] for depth in range(max_depth+1)]

方法二:深度优先搜索算法

  我们使用二叉树的中序遍历算法,遍历顺序为“中右左”,这样把整个二叉树遍历一次,在遍历途中,记录下每个深度的第一个数值,就是右视图的值。

 1 class Solution(object):
 2     def rightSideView(self, root):
 3         rightmost_value_at_depth = dict() # 深度为索引,存放节点的值
 4         max_depth = -1
 5 
 6         stack = [(root, 0)]
 7         while stack:
 8             node, depth = stack.pop()
 9 
10             if node is not None:
11                 # 维护二叉树的最大深度
12                 max_depth = max(max_depth, depth)
13 
14                 # 如果不存在对应深度的节点我们才插入
15                 rightmost_value_at_depth.setdefault(depth, node.val)
16 
17                 stack.append((node.left, depth+1))
18                 stack.append((node.right, depth+1))
19 
20         return [rightmost_value_at_depth[depth] for depth in range(max_depth+1)]

猜你喜欢

转载自www.cnblogs.com/fsencen/p/leetcode4.html