vector变量存储每一层的元素vector<vector<int> > ans; 定义队列queue push front中序遍历每一层的元素,queue.size()判断每一层是否为空,queue<TreeNode*> q; q.push(pRoot);
push() pop() size() empty() front() back()
queue<string> q;
q.push("Hello World!");
q.push("China");
cout<<q.front()<<endl;
queue<string> q;
q.push("Hello World!");
q.push("China");
q.pop();
cout<<q.front()<<endl;
queue<string> q;
cout<<q.size()<<endl;
q.push("Hello World!");
q.push("China");
cout<<q.size()<<endl;
queue<string> q;
cout<<q.empty()<<endl;
q.push("Hello World!");
q.push("China");
cout<<q.empty()<<endl;
queue<string> q;
q.push("Hello World!");
q.push("China");
cout<<q.front()<<endl;
q.pop();
cout<<q.front()<<endl
queue<string> q;
q.push("Hello World!");
q.push("China");
cout<<q.back()<<endl;
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 class Solution { 12 public: 13 vector<vector<int> > Print(TreeNode* pRoot) { 14 vector<vector<int> > ans; 15 if(pRoot == NULL) 16 return ans; 17 queue<TreeNode*> q; 18 q.push(pRoot); 19 while(!q.empty()){ 20 int size = q.size();//读取每一层的元素的数量,queue的size()函数返回队列中元素的个数,返回值类型为unsigned int 21 vector<int> levelelem; 22 while(size--){ 23 TreeNode* t = q.front();//返回值为队列中的第一个元素,也就是最早、最先进入队列的元素。 24 q.pop(); 25 levelelem.push_back(t->val); 26 if(t->left != NULL) q.push(t->left); 27 if(t->right != NULL) q.push(t->right); 28 } 29 ans.push_back(levelelem); 30 } 31 return ans; 32 } 33 };
https://blog.csdn.net/zjwreal/article/category/8762404
https://blog.csdn.net/ZHLZYF/article/details/83280481
剑指offer60:把二叉树打印成多行。上到下按层打印二叉树。
原文:https://www.cnblogs.com/wxwhnu/p/11434562.html