【LeetCode】199. Binary Tree Right Side View 解题报告(Python)

标签: LeetCode


题目地址:https://leetcode.com/problems/binary-tree-right-side-view/description/

题目描述:

Given 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.

For example:
Given the following binary tree, 1 <---
/ \
2 3 <---
\ \
5 4 <--- You should return [1, 3, 4].

题目大意

打印出二叉树每层的最右边的元素。

解题方法

这个题就是102. Binary Tree Level Order Traversal翻版啊!上个题是要直接打印每层的元素,这个是要每层元素的最右边元素,所以可以使用之前的解法,然后再把每层的给取出来嘛~~

递归解法:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
self.levelOrder(root, 0, res)
return [level[-1] for level in res] def levelOrder(self, root, level, res):
if not root: return
if len(res) == level: res.append([])
res[level].append(root.val)
if root.left: self.levelOrder(root.left, level + 1, res)
if root.right: self.levelOrder(root.right, level + 1, res)

非递归解法,使用队列。

这个解题的技巧在于,queue其实也可以用[-1]直接找到这个层的最后一个元素。

每次进行while循环,都是开始了新的一层,for循环的巧妙在于,直接遍历队列中已有的元素,也就是上层的元素。这样的话就直接把上层的遍历完了,新的层也加入了队列。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
if not root: return res
queue = collections.deque()
queue.append(root)
while queue:
res.append(queue[-1].val)
for i in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res

日期

2018 年 3 月 14 日 –霍金去世日

最新文章

  1. useful Ansible commands
  2. MySQL5.6忘记root用户名和密码
  3. Bestcoder#5 1003
  4. viso2010从mysql中导出ER图
  5. android selector(转)
  6. 玩转PowerShell第三节——【SCOM Maintenance Mode】-技术&amp;分享
  7. codereview介绍
  8. SQL Server Alwayson创建代理作业注意事项
  9. 深入理解String的关键点和方法
  10. 一个Web前端自学者的自述
  11. linux 下使用 tc 模拟网络延迟和丢包
  12. 运行go服务器后台挂起(不看调试信息)
  13. leetcode — permutations-ii
  14. npm --save-dev 和--save 参数的区别
  15. 【团队】EasyKing的实现_2
  16. javaweb中的乱码问题
  17. javascript中的require、import和export模块文件
  18. Android-Kotlin-set/get方法的使用
  19. 【题解】 bzoj1088: [SCOI2005]扫雷Mine (神奇的做法)
  20. WordPress 获取指定分类ID的分类信息

热门文章

  1. 完美png图片添加水印类
  2. jmeter非GUI(cmd命令行)模式的压测和输出测试报告
  3. 巩固javaweb第十二天
  4. 日常Java 2021/9/27
  5. A Child&#39;s History of England.18
  6. day02 Rsyuc备份服务器
  7. C语言大小端判定
  8. Flink(四)【IDEA执行查看Web UI】
  9. ACE_Message_Block实现浅析
  10. SpringBoot 整合 spring security oauth2 jwt完整示例 附源码