这道题看了一会发现其实使用BFS会非常简单:

/**
 * 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> res;
        if(!root) return res;
        
        queue<TreeNode *> queue;
        queue.push(root);
        
        while(!queue.empty())
        {
            int size = queue.size();
            for(int i = 0;i < size;i++)
            {
                TreeNode * curr = queue.front();
                queue.pop();
                if(i == size - 1)
                    res.push_back(curr->val);
                if(curr->left) queue.push(curr->left);
                if(curr->right) queue.push(curr->right);
            }
        }
        
        return res;
    }
};

上面的程序存在一个可以优化的地方,每次向res中添加元素时不用在for循环判断,因为queue中我们知道在最后那个元素。优化后的代码如下:

/**
 * 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> res;
        if(!root) return res;
        
        queue<TreeNode *> queue;
        queue.push(root);
        
        while(!queue.empty())
        {
            res.push_back(queue.back()->val);
            int size = queue.size();
            for(int i = 0;i < size;i++)
            {
                TreeNode * curr = queue.front();
                queue.pop();
                if(curr->left) queue.push(curr->left);
                if(curr->right) queue.push(curr->right);
            }
        }
        
        return res;
    }
};