【剑指offer】把二叉树打印成多行
题目链接:把二叉树打印成多行
题意:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
题解:用一个队列,每层压入队列,再放入数组里。层序遍历。
代码:
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 vector<int> level; 16 if(pRoot == NULL) return ans; 17 18 queue<TreeNode*> q; 19 q.push(pRoot); 20 int cnt = 0; 21 while(!q.empty()){ 22 level.clear(); 23 cnt = q.size(); 24 while(cnt--){ 25 TreeNode* node = q.front(); 26 level.push_back(node->val); 27 if(node->left) q.push(node->left); 28 if(node->right) q.push(node->right); 29 q.pop(); 30 } 31 ans.push_back(level); 32 } 33 return ans; 34 } 35 36 };