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

这是一道medium的题,但是刚开始感觉不难。首先看到这道题的第一反应就是层序遍历,用队列。以前考研的时候看到过层序遍历,不过真心不记得了。后来自己想偏了,又说想用栈。

这道题就是把每一层的节点从左到右的入队(此时就可以计算一下队的大小,这个我一直没有想到,这样就可以计算出每一层有多少个节点了。),然后取最后一个节点的值入结果vector。假设我们第一层扫描完了(即它的孩子已经入队了),每扫描完了以后就会删掉你扫描的节点,那么当你把第一层的节点扫描完,第二层节点已经入队且第一层的节点已经被删除掉了,此时队列里只有第二层的节点,然后我们取最后一个的值入结果vector,就是最右的(因为我们是从左到右入队的)。同理,扫描第二层节点,扫描完了以后第二层节点已经全部被删除,队列里只有第三层节点。直至队列里没有节点了,说明新的一层一个节点没有,那就是树到底了。附代码。(这道题自己没做出来,后来参考别人的。。

using namespace std;
/**
* 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 val=,sizequeue=;
vector<int> result;
if(root==NULL) return result;
queue<TreeNode> TreeQueue;
TreeQueue.push(*root);
while(!TreeQueue.empty()){ val=(TreeQueue.back()).val;
result.push_back(val);
sizequeue=TreeQueue.size();
for(int i=;i<sizequeue;i++){ *root=TreeQueue.front();
TreeQueue.pop(); if(root->left!=NULL) TreeQueue.push(*(root->left));
if(root->right!=NULL) TreeQueue.push(*(root->right)); } }
return result;
}
};

最新文章

  1. .net学习笔记----HttpRequest,WebRequest,HttpWebRequest区别
  2. 字符编码笔记:ASCII,Unicode和UTF-8 转
  3. How does controller listen to service?
  4. C# 读取指定URL的内容
  5. Python LOGGING使用方法
  6. ZOJ 3261 Connections in Galaxy War(逆向并查集)
  7. LESS学习总结
  8. linux环境下deb格式文件转换成rpm格式
  9. Web前端相关资源
  10. docker环境中安装node、pm2,映射项目文件守护程序
  11. SQLite multiple threads
  12. 分布式队列celery 异步----Django框架中的使用
  13. Sublime Text使用中的一些心得
  14. vue教程1-04 事件 v-on:click=&quot;函数&quot;
  15. Java开发中常用的设计模式(一)---工厂模式
  16. 详解ABBYY FineReader 12扫描亮度设置
  17. mongo数据库查询结果不包括_id字段方法
  18. Angular报错
  19. docker login 报错 Error response from daemon: Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password
  20. aclocal: error: aclocal: file &#39;/usr/local/share/aclocal/wxwin.m4&#39; does not exist

热门文章

  1. Java 中基本类型和字符串之间的转换
  2. vijos1760题解
  3. geotrellis使用(二十九)迁移geotrellis至1.1.1版
  4. 原生JS的HTTP请求
  5. gulp总结
  6. FineReport填报分页设置
  7. HelloGitHub.com 网站开源了
  8. Java之字符串String,StringBuffer,StringBuilder
  9. Luogu 2245 星际导航(最小生成树,最近公共祖先LCA,并查集)
  10. Spark的误解-不仅spark是内存计算,hadoop也是内存计算