zoukankan      html  css  js  c++  java
  • something about basic usage of vector,queue

    1.for a two dimension vector, we must assign at least the first dimension of the vector

    2.each dimension of an inner vector can be different

    3.if you don't want to set a volume for vector<vector<int> > for uncertainness, you can just use a method like append to implement the structure,which is applied inBinary Tree Level Order Traversal,

    4.about queue: to add an element, q.push(element); to get the first element, q.front(); to erase the first element, q.pop();

    5.how to differ elements from different layers?

        use two queues rather than one

    code:

    class Solution{
    public:
        vector<vector<int> > levelOrder(TreeNode*root){
            vector<vector<int> > matrix;
            if(root == NULL){
                return matrix;
            }
            queue<TreeNode*> qNode[2];
            //int row = 0;
            qNode[0].push(root);
            int index = 0;
    		
            while((!qNode[0].empty())||(!qNode[1].empty())){
    			 vector<int>mm;
                switch(index){
            case(0):
                while(!qNode[0].empty()){
                    TreeNode* tmp = qNode[0].front();
                    qNode[0].pop();
                  
    				mm.push_back(tmp->val);
                    if(tmp->left != NULL){
                        qNode[1].push(tmp->left);
                    }
                    if(tmp->right != NULL){
                        qNode[1].push(tmp->right);
                    }
                }
                index = 1 - index;
    			matrix.push_back(mm);
                //++row;
                break;
            case(1):
    			//vector<vector<int> >m;
                while(!qNode[1].empty()){
                    TreeNode* tmp = qNode[1].front();
                    qNode[1].pop();
                    //matrix[row].push_back(tmp->val);
    				mm.push_back(tmp->val);
                    if(tmp->left != NULL){
                        qNode[0].push(tmp->left);
                    }
                    if(tmp->right!=NULL){
                        qNode[0].push(tmp->right);
                    }
                }
                index = 1 - index;
                //++row;
    			matrix.push_back(mm);
                }
            }
             return matrix;
        }
    
    };
    

      

  • 相关阅读:
    aa
    MySQL5.8下载及安装——免安装版
    eclipse中修改项目名
    利用kibana学习 elasticsearch restful api (DSL)
    https://www.cnblogs.com/shwee/p/9084535.html
    springboot+mybatis实现动态切换数据源
    docker-machine命令安装
    Docker 安装 RabbitMq
    yum 找不到程序,yum更换国内阿里源
    CentOS安装etcd和flannel实现Docker跨物理机通信
  • 原文地址:https://www.cnblogs.com/warmfrog/p/3699221.html
Copyright © 2011-2022 走看看