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

其实题目的意思就是相当于二叉树每一行的最右边的一个元素,那么简单,先bfs后取每一个数组的最后一位数就可以了,代码如下:

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
int dep = -;
bfs(root, dep + );
vector<int> res;
for(int i = ; i < ret.size(); ++i){
res.push_back(ret[i][ret[i].size() - ]);
}
return res;
} void bfs(TreeNode * root, int depth)
{
if(root == NULL) return;
if(depth < ret.size()){
ret[depth].push_back(root->val);
}else{
vector<int>tmp;
ret.push_back(tmp);
ret[depth].push_back(root->val);
}
if(root->left)
bfs(root->left, depth + );
if(root->right)
bfs(root->right, depth + );
}
private:
vector<vector<int>> ret;
};

java版本的代码如下所示,同样是BFS之后再取最后一位组成一个数组:

 public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
List<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
bfs(ret, root, );
for(int i = ; i < ret.size(); ++i){
res.add(ret.get(i).get(ret.get(i).size() - ));
}
return res;
} public void bfs(List<List<Integer>> ret, TreeNode root, int dep){
if(ret.size() <= dep){
ret.add(new ArrayList<Integer>());
}
ret.get(dep).add(root.val);
if(root.left != null)
bfs(ret, root.left, dep + );
if(root.right != null)
bfs(ret, root.right, dep + );
}
}

最新文章

  1. [NOIP2014]自测
  2. linux权限系统
  3. IIS 7.0 部署MVC
  4. STM32 flash 内存分布介绍
  5. 在ubuntu上配置apue的运行环境
  6. Linux:设置alias永久生效
  7. java新手笔记7 找最小、最大、排序
  8. SGU 解题报告
  9. Sqlserver2012 alwayson部署攻略
  10. Remove掉Request.QueryString
  11. javascript 下拉列表 自己主动取值 无需value
  12. vue路由组件群
  13. java TreeSet应用
  14. JavaWeb项目架构之Kafka分布式日志队列
  15. const和static readonly的区别
  16. [NOIp2009] $Hankson$ 的趣味题
  17. 【BZOJ2298】[HAOI2011]problem a
  18. maven 项目 查询部分关心的字段
  19. (转)Android学习路线总结,绝对干货
  20. java8 集合神操作

热门文章

  1. R&amp;python机器学习之朴素贝叶斯分类
  2. 用django写个CMS系统
  3. php mysqli扩展库之预处理操作
  4. 流量分析系统---flume(测试flume+kafka)
  5. 前端之 Ajax(补)
  6. Linux进程优先级查看及修改
  7. iOS CMTimeMake 和 CMTimeMakeWithSeconds 学习
  8. 【HackerRank】 Game Of Thrones - I
  9. CSS3展开带弹性动画的手风琴菜单
  10. C#中利用WebBrowser控件,获得HTML源码