分析
由于右视图只能看见最右边的节点,也就是也层最后一个节点,可以利用层序遍历,把最后一个节点加入ans中即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if(!root)return ans;
queue<TreeNode*> q;
q.push(root);
int count=1;
while(q.size()){
auto t=q.front();
q.pop();
if(t->left)q.push(t->left);
if(t->right)q.push(t->right);
count--;
if(count==0){
count=q.size();
ans.emplace_back(t->val);
}
}
return ans;
}
};