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; } };