44.分行从上往下打印二叉树

 https://www.acwing.com/video/167/

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> printFromTopToBottom(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> level;//每一层的矩阵
        if(!root)  return res;
        
        //定义一个辅组队列
        queue<TreeNode*> q;
        q.push(root);//初始化res
        q.push(nullptr); //root层的标识符
        
        
        while(q.size())
        {
            TreeNode* t = q.front();
            //cout<< "t1=" << q.front() <<' ' << "b1=" << q.back() << "size1=" << q.size() << endl;
            q.pop();
            //cout<< "t2=" << q.front() <<' ' << "b2=" << q.back() << "size2=" << q.size() << endl;
            //cout<< "t="<< t << endl;
            
            if(!t)//遍历完了一整行 
            {
                //if(level.empty())  break;含义:
                //下一层已经没有节点了,遍历所有点了。
                if(level.empty())  break;
                res.push_back(level); 
                level.clear();
                q.push(nullptr);//一层结束后,在后面加上null
                continue;//跳出if循环,重新从while开始执行
            }
            //否则要进行扩展
            level.push_back(t->val);
            
            //cout<< "t->val="<< t->val << endl;
            
            if(t->left) q.push(t->left);    //  t->left ==NULL,这句不执行
            if(t->right) q.push(t->right);  //  ==NULL,这句不执行
            
            //cout<< "t3=" << q.front() <<' ' << "b2=" << q.back() << endl;
            //cout<< "size=" << q.size() << endl;
        }
        
        return res;
    }
};
带女朋友搬家新家条件不好,累到女朋友了,让女朋友受苦了,特此明志:每天学习,明年这个时候(20190812)让女朋友住上大房子,永远年轻,永远热泪盈眶,很多人都是这样,他们都把自己当成身在梦中一样,浑浑噩噩地过日子,只有痛苦或爱或危险可以让他们重新感到这个世界的真实。
原文地址:https://www.cnblogs.com/make-big-money/p/12312302.html