My easy understanding C++ code by level order traversal


  • 0
    B

    My easy understanding C++ code by level order traversal

    '''
    class Solution {
    public:
    vector<int> rightSideView(TreeNode* root) {
    vector<int> res;
    if(root == nullptr) return res;
    queue<TreeNode*> queue;
    queue.push(root);
    int count = 1;
    while(!queue.empty()){
    TreeNode* cur = queue.front();
    if(cur -> left != nullptr) queue.push(cur -> left);
    if(cur -> right != nullptr) queue.push(cur -> right);

            if(count == 1){
                res.push_back(cur -> val);
                queue.pop();
                count--;
            }
            else if(count > 1){
                queue.pop();
                count--;
            }
            
            if(count == 0) count = queue.size();
        }
        return res;
    }
    

    };
    '''


Log in to reply
 

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