199. Binary Tree Right Side View

//关键就是把每一层的节点数记下来,当循环完当层节点数再输出队列的最后一位耗时4ms



class Solution {
public:
    
    vector<int> rightSideView(TreeNode* root) {

    vector<int> res;
                if(!root)return res;
        queue<TreeNode *> q;
        q.push(root);
        int count=1;
        while(!q.empty()){
            int tmp=count;
            count=0;
             res.push_back(q.back()->val);
            for(int i=0;i<tmp;i++){
                TreeNode *c=q.front();
                q.pop();
                if(c->left){q.push(c->left);++count;}
                if(c->right){q.push(c->right);++count;}
            }
           
        }
        return res;
    }
};

 

posted @ 2018-12-28 01:08  keep!  阅读(107)  评论(0编辑  收藏  举报
Live2D