面试题61 把二叉树打印成多行
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
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> > vec; 15 if(pRoot == NULL) return vec; 16 17 queue<TreeNode*> q; 18 q.push(pRoot); 19 20 while(!q.empty()) 21 { 22 int lo = 0, hi = q.size(); 23 vector<int> c; 24 while(lo++ < hi) 25 { 26 TreeNode *t = q.front(); 27 q.pop(); 28 c.push_back(t->val); 29 if(t->left) q.push(t->left); 30 if(t->right) q.push(t->right); 31 } 32 vec.push_back(c); 33 } 34 return vec; 35 } 36 };