[LeetCode]199. Binary Tree Right Side View
2016-03-13 11:48
211 查看
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
思路:层序遍历二叉树,把每一层的最后一个节点存进结果list中
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return
[1, 3, 4].
思路:层序遍历二叉树,把每一层的最后一个节点存进结果list中
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) return res; int thislevel = 1; int nextlevel = 0; LinkedList<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while(q.isEmpty() == false) { while(thislevel > 0) { TreeNode temp = q.poll(); thislevel--; if (thislevel == 0) res.add(temp.val); if(temp.left != null) { nextlevel++; q.offer(temp.left); } if(temp.right != null) { nextlevel++; q.offer(temp.right); } } thislevel = nextlevel; nextlevel = 0; } return res; } }
相关文章推荐
- Android如何在Framework层使用解锁代码
- 使用jQuery.form插件,实现完美的表单异步提交
- 使用jQuery操作HTML的table表格的实例解析
- 关于如何修改PreferenceFragment中默认的字体颜色和大小
- HttpSession
- 第3周-项目3(2)-输出星号图
- 《你必须知道的495个C语言问题》读书笔记之第15-20章:浮点数、风格、杂项
- Python Flask开源博客系统Blog_mini
- 贪心算法,今年暑假不AC
- VMARE 12 安装黑苹果 OS X 10.11
- Blog_mini完整部署文档
- 在Ubuntu上使用apt-get安装MySQL+安全优化
- 在Ubuntu上部署开源博客系统Blog_mini
- 在Ubuntu上源码安装MySQL+安装问题解决+安全优化
- linux中c/c++连接mysql示例程序
- 多线程 : ThreadLocal 实现线程间共享变量隔离例子
- 我们大多数是迷茫众生,唯有让自我人性更加丰满…唯有让灵魂找回清净的本心…让生命在每个瞬间不再继续迷失
- Django实战教程 分页列表
- JDBC连接执行 MySQL 存储过程报权限错误:User does not have access to metadata required to determine stored procedur
- win7 vs2010 安装cocos2d-x