首页 技术 正文
技术 2022年11月21日
0 收藏 595 点赞 4,028 浏览 1222 个字

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;
}
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,023
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,360
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,143
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,774
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,853