题目

题解

二叉树结构如下:

//Definition for a binary tree node.
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
//本题借鉴#102层次遍历
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        if(!root) return res;
        queue<TreeNode*> q{{root}};
        while(!q.empty()){
            res.push_back(q.back()->val);//和#102的区别,取q队尾的值
            for(int i=q.size(); i>0; i--){
                TreeNode* cur = q.front();q.pop();
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
            }
        }
        return res;
    }
};