题目:按之字形顺序打印二叉树
要求:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/* 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 queue<TreeNode*> q; 10 q.push(pRoot); 11 TreeNode *temp = pRoot; 12 int currentLevel= 1; 13 int nextLevel = 0; 14 int flag = 1; 15 while(!q.empty()){ 16 temp = q.front(); 17 q.pop(); 18 subRes.push_back(temp->val); 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 if(flag == -1) 30 reverse(subRes.begin(), subRes.end()); 31 res.push_back(subRes); 32 subRes.clear(); 33 currentLevel = nextLevel; 34 nextLevel = 0; 35 flag = -1 * flag; 36 } 37 } 38 return res; 39 } 40 };