Simple C++ solution with 2 queues


  • 0
    G
        vector<int> rightSideView(TreeNode* root) {
            vector<int> r;
            if (!root) return r;
            
            queue<TreeNode*> q, q_next; // current level and next level nodes
            q.push(root);
    
            while (!q.empty()) {
                TreeNode* temp = q.front();
                q.pop();
                if (temp->left) q_next.push(temp->left);
                if (temp->right) q_next.push(temp->right);
                if (q.empty()) {        // current level is done. Move on to next level
                    r.push_back(temp->val);
                    q = q_next;
                    while (!q_next.empty()) q_next.pop();
                }
            }
            return r;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.