c++ bfs


  • 0
    B
        vector<int> rightSideView(TreeNode *root) {
            queue<pair<TreeNode *, int>> q;
            q.push({root, 0});
            vector<int> result;
            while (!q.empty()) {
                const auto &p = q.front();
    
                if (p.first) {
                    if (result.size() > p.second) {
                        result[p.second] = p.first->val;
                    } else {
                        result.push_back(p.first->val);
                    }
                    q.push({p.first->left, p.second + 1});
                    q.push({p.first->right, p.second + 1});
                }
    
                q.pop();
            }
            return result;
        }
    

    not much to explain, pretty straightforward.


Log in to reply
 

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