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

C++Leetcode199:二叉树的右视图

2019-03-04 13:02 260 查看

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

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

思路
1、BFS

实现方法
一、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) {
vector<int> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int count=q.size();
res.push_back(q.back()->val);	//取队列的末尾元素值
while(count>0){
TreeNode* top=q.front();
q.pop();
count--;
if(top->left) q.push(top->left);
if(top->right) q.push(top->right);
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: