Clear c++ bfs solution


  • 5
    V
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        if(!root)
            return res;
        queue<TreeNode*> que;
        que.push(root);
        int count = 1;
        while(!que.empty()){
            TreeNode *temp = que.front();
            que.pop();
            if(temp->left)
                que.push(temp->left);
            if(temp->right)
                que.push(temp->right);
            count--;
            if(count == 0){
                count = que.size();
                res.push_back(temp->val);
            }
        }
        return res;
    }

  • 0
    J

    vector<int> rightSideView(TreeNode* root) {
    vector<int> res;
    if(!root)
    return res;
    queue<TreeNode*> que;
    que.push(root);
    int count = 1;
    while(!que.empty()){
    TreeNode *temp = que.front();
    que.pop();
    if(temp->left)
    que.push(temp->left);
    if(temp->right)
    que.push(temp->right);
    count--;
    if(count == 0){
    count = que.size();
    res.push_back(temp->val);
    }
    }
    return res;
    }


Log in to reply
 

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