标签:== root queue cto pre while tor -- color
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
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> > res; 15 vector<int> temp_vec; 16 queue<TreeNode*> q; 17 if(pRoot==nullptr) return res; 18 q.push(pRoot); 19 while(!q.empty()){ 20 int len=q.size(); 21 temp_vec.clear(); 22 //只存每一层的queue 23 while(len--){ 24 TreeNode* tmp=q.front(); 25 temp_vec.push_back(tmp->val); 26 q.pop(); 27 if(tmp->left) q.push(tmp->left); 28 if(tmp->right) q.push(tmp->right); 29 } 30 res.push_back(temp_vec); 31 } 32 return res; 33 } 34 35 };
标签:== root queue cto pre while tor -- color
原文地址:https://www.cnblogs.com/pacino12134/p/11263437.html