My easy code using queue in 4ms


  • 0
    H
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            int max = 0;
            vector<int> res;
            queue<pair<TreeNode*,int> > q;
            q.push(pair<TreeNode*,int>(root,1));
            while( !q.empty() ){
    			pair<TreeNode*,int> pp = q.front();
                if( pp.second >  max ){
                    max = pp.second;      
                    res.push_back(pp.first->val);
                }
                if( pp.first->right )
                    q.push(pair<TreeNode*,int> (pp.first->right,pp.second+1));
                if( pp.first->left )
                    q.push(pair<TreeNode*,int> (pp.first->left,pp.second+1) );
                q.pop();
            }
            return res;
        }
    };

Log in to reply
 

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