剑指offer---把二叉树打印成多行
题目:把二叉树打印成多行
要求:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
* 注意: 此题要求返回二维数组,若需要返回一维数组,请点击这里
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { } };
解题代码:
1 class Solution { 2 public: 3 vector<vector<int> > Print(TreeNode* pRoot) { 4 vector<vector<int> > res; 5 vector<int> subRes; 6 if(pRoot == nullptr) 7 return res; 8 9 int currentLevel = 1; 10 int nextLevel = 0; 11 queue<TreeNode*> q; 12 q.push(pRoot); 13 14 while(!q.empty()){ 15 TreeNode* temp = q.front(); 16 subRes.push_back(temp->val); 17 q.pop(); 18 19 if(temp->left){ 20 q.push(temp->left); 21 nextLevel++; 22 } 23 if(temp->right){ 24 q.push(temp->right); 25 nextLevel++; 26 } 27 currentLevel--; 28 if(currentLevel == 0){ 29 res.push_back(subRes); 30 subRes.clear(); 31 currentLevel = nextLevel; 32 nextLevel = 0; 33 } 34 } 35 return res; 36 } 37 };