题目:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
代码:
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> > LIST; 15 if(pRoot == NULL) return LIST; 16 queue<TreeNode*> q1; 17 queue<TreeNode*> q2; 18 vector<int> list; 19 q1.push(pRoot); 20 int pattern = 1; 21 list.push_back(pRoot->val); 22 LIST.push_back(list); 23 list.clear(); 24 while(!(q1.empty() && q2.empty())) { 25 TreeNode* temp; 26 if(pattern == 1){ 27 temp = q1.front(); 28 q1.pop(); 29 if(temp->left){ 30 q2.push(temp->left); 31 list.push_back(temp->left->val); 32 } 33 if(temp->right){ 34 q2.push(temp->right); 35 list.push_back(temp->right->val); 36 } 37 if(q1.empty() && !list.empty()){ 38 LIST.push_back(list); 39 list.clear(); 40 pattern = 2; 41 } 42 } 43 else { 44 temp = q2.front(); 45 q2.pop(); 46 if(temp->left){ 47 q1.push(temp->left); 48 list.push_back(temp->left->val); 49 } 50 if(temp->right){ 51 q1.push(temp->right); 52 list.push_back(temp->right->val); 53 } 54 if(q2.empty() && !list.empty()){ 55 LIST.push_back(list); 56 list.clear(); 57 pattern = 1; 58 } 59 } 60 } 61 return LIST; 62 } 63 };
我的笔记:
利用两个队列完成层序遍历即可。