题目
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [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;
}
};