【剑指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         
21         bool flag = false;
22         while(!q.empty()){
23             level.clear();
24             int len = q.size();
25             for(int i = 0; i < len ;i++){
26                 TreeNode* temp = q.front();
27                 q.pop();
28                 level.push_back(temp->val);
29                 if(temp->left)    q.push(temp->left);
30                 if(temp->right)    q.push(temp->right);
31             }
32             if(flag)    reverse(level.begin(),level.end());
33             ans.push_back(level);
34             flag = !flag;
35         }
36         return ans;
37     }
38     
39 };
原文地址:https://www.cnblogs.com/Asumi/p/12423765.html