您的位置:首页 > 编程语言 > C语言/C++

C/C++编程题刷题:leetcode 199. 二叉树的右视图

2020-08-23 10:04 141 查看

199. 二叉树的右视图

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

[code]输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

1            <---
/   \
2     3         <---
\     \
5     4       <---
[code]/**
* 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) {
if(!root) return {};
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
vector<int> res;
int tmp;
while(q.size()){
auto t = q.front();
q.pop();
if(t){
tmp = t->val;
if(t->left)  q.push(t->left);
if(t->right) q.push(t->right);
}
else{
res.push_back(tmp);
if(q.size())
q.push(nullptr);
}
}
return res;
}
};

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: