https://leetcode.com/problems/binary-tree-right-side-view/description/?envType=study-plan-v2&envId=top-interview-150

Approach 1: BFS: Two Queues

Algorithm

/**
 * 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) {
        if (root == nullptr) return vector<int>();

        deque<TreeNode*> nextLevel{root};
        deque<TreeNode*> currLevel;
        vector<int> rightside;

        TreeNode* node = nullptr;
        while (!nextLevel.empty()){
            currLevel = nextLevel;
            nextLevel.clear();

            while (!currLevel.empty()){
                node = currLevel.front();
                currLevel.pop_front();

                if (node->left != nullptr) nextLevel.push_back(node->left);
                if (node->right != nullptr) nextLevel.push_back(node->right);
            }
            rightside.push_back(node->val);
        }
        return rightside;
    }
};

Complexity Analysis

Approach 2: BFS: One Queue + Sentinel

Algorithm

/**
 * 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) {
        if (root == NULL) return vector<int>();

        queue<TreeNode*> queue;
        queue.push(root);
        queue.push(NULL);
        TreeNode *prev, *curr = root;
        vector<int> rightside;

        while (!queue.empty()){
            prev = curr;
            curr = queue.front();
            queue.pop();

            while (curr != NULL){
                // add child nodes in the queue
                if(curr->left != NULL){
                    queue.push(curr->left);
                }
                if(curr->right != NULL){
                    queue.push(curr->right);
                }
                prev = curr;
                curr = queue.front();
                queue.pop();
            }

            // the current level is finished
            // and prev is the rightmost element
            rightside.push_back(prev->val);

            // add a sentinel to mark the end
            // of the next level
            if (!queue.empty()) queue.push(NULL);
        }
        return rightside;
    }
};

Complexity Analysis