199. Binary Tree Right Side View
2016-04-19 02:09
309 查看
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,
You should return
Solution 1
Solution 2
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return
[1, 3, 4].
Solution 1
// BFS public List<Integer> rightSideView(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); Queue<TreeNode> q = new LinkedList<TreeNode>(); if (root == null) { return res; } q.add(root); while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { TreeNode temp = q.poll(); if (i == size - 1) { res.add(temp.val); } if (temp.left != null) { q.offer(temp.left); } if (temp.right != null) { q.offer(temp.right); } } } return res; }
Solution 2
//Better DFS public static List<Integer> rightSideView2(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); rightView(root, result, 0); return result; } public static 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); }
相关文章推荐
- 一个通用的有限状态机(FSM)框架
- 基础03 JVM到底在哪里?
- wifi无法连接华为Mate8 热点问题
- 装饰者设计模式
- 常用CSS HACK
- ubuntu更新Jar包中的文件
- Material Design之自定义Material主题及Toolbar
- ThinkPHP3.2.3学习笔记3---视图
- [JAVA]Listener监听模式的学习
- 获取客户端浏览器版本
- 解决包冲突问题
- LeetCode 78. Subsets
- 带你实现开发者头条(二) 实现左滑菜单
- Linux版本选择(CentOS)
- 如何给maven项目增加新的jar包(从服务器上下载)---通过从web页面复制信息
- 动态链接库和静态链接库区别
- PostGIS 快速入门(转)
- js动态创建样式: style 和 link
- PHP mysqli连接MySQL数据库
- Android OpenGL 开始篇 <1>