Leetcode | Binary Tree Right Side View
来源:互联网 发布:阿里云搭建ss 无网 编辑:程序博客网 时间:2024/06/03 18:50
question:
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].
normal solution:
使用用广度遍历 遍历到最右边的点 则加入list
public List<Integer> rightSideView(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); LinkedList<TreeNode> list= new LinkedList<TreeNode>(); if(root==null) return res; list.add(root); TreeNode tmp=null; while(!list.isEmpty()) { int len=list.size(); while(len!=0) { tmp=list.pop(); if(tmp.left!=null) list.add(tmp.left); if(tmp.right!=null) list.add(tmp.right); len--; } res.add(tmp.val); } return res;}
a better solution
深度遍历 先遍历最右结点是否存在 存在则加入list 否则遍历左结点的右结点 循环反复 最终得到结果
public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); rightView(root, result, 0); return result;}public void rightView(TreeNode curr, List<Integer> result, int currDepth){ if(curr == null){ return; } if(currDepth == result.size()){ result.add(curr.val); } rightView(curr.right, result, currDepth + 1); rightView(curr.left, result, currDepth + 1);}
0 0
- [leetcode][tree] Binary Tree Right Side View
- LeetCode OJ Binary Tree Right Side View
- LeetCode:Binary Tree Right Side View
- [leetcode] 199 Binary Tree Right Side View
- [LeetCode]199.Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View
- LeetCode | Binary Tree Right Side View
- [LeetCode] Binary Tree Right Side View
- LeetCode: Binary Tree Right Side View
- [leetcode]48 Binary Tree Right Side View
- [leetcode] Binary Tree Right Side View
- leetcode-199 Binary Tree Right Side View
- [LeetCode]Binary Tree Right Side View
- 199Binary Tree Right Side View-LeetCode
- Binary Tree Right Side View--LeetCode
- [LeetCode]Binary Tree Right Side View
- [LeetCode 199]Binary Tree Right Side View
- leetcode: Binary Tree Right Side View
- 使用tinymini210开发远程的温度监控系统,实现C#和安卓客户端显示数据和控制
- java基础学习(4)
- ThinkPHP访问数据库的方法
- 算法导论——2.1-2选择排序
- 初中OJ1837. 【NOIP2009TG】靶形数独
- Leetcode | Binary Tree Right Side View
- 一道c++面试题的思考与学习(类内存布局)
- 大数据Spark “蘑菇云”行动第101课:Hive性能调优之企业级数据倾斜解决方案及对Job数目的优化
- 好帖子好地址_即时通讯相关
- 关于Faster R-CNN的一切——笔记1:R-CNN
- 1027. 打印沙漏(20)
- js写一个好用的数组查找方法
- win10 C盘根目录无法创建文件
- SQL查询语句精华使用简要