原题目:https://leetcode-cn.com/problems/binary-tree-right-side-view/
思路;
BFS遍历,每次存入每一层的最后一个元素
代码:
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
if(root==NULL) return {};
vector<int> ans;
int size;
queue<TreeNode*> q;
q.push(root);
TreeNode* s;
while(!q.empty()){
size = q.size();
for(int i=0;i<size;i++){
s = q.front();q.pop();
if(i==size-1) ans.push_back(s->val);
if(s->left) q.push(s->left);
if(s->right) q.push(s->right);
}
}
return ans;
}
};