按之字形顺序打印二叉树

题目描述

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
 
思路:基于按层遍历,增加一个flag标记,如果是偶数层就置逆以后再输出
 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 void reverse(vector<int> &tmp)
12 {
13     int left=0;
14     int right=tmp.size()-1;
15     while(left<right)
16     {
17         int a=tmp[left];
18         tmp[left]=tmp[right];
19         tmp[right]=a;
20         ++left;
21         --right;
22     }
23 }
24 class Solution {
25 public:
26     vector<vector<int> > Print(TreeNode* pRoot) {
27         vector<vector<int>> res;
28         if(pRoot==NULL)return res;
29         bool flag=true;
30         std::queue<TreeNode *> que;
31         que.push(pRoot);
32         TreeNode *last=pRoot;
33         TreeNode *nlast=pRoot;
34         vector<int> tmp;
35         while(que.size())
36         {
37             TreeNode *p=que.front();
38             que.pop();
39             tmp.push_back(p->val);
40             if(p->left)
41             {
42                 que.push(p->left);
43                 nlast=p->left;
44             }
45             if(p->right)
46             {
47                 que.push(p->right);
48                 nlast=p->right;
49             }
50             if(p==last)
51             {
52                 if(flag==false)reverse(tmp);//置逆
53                 res.push_back(tmp);
54                 tmp.clear();
55                 flag=!flag;
56                 last=nlast;
57             }
58         }
59         return res;
60     }
61 };

 

posted @ 2018-02-04 11:24  jeysin  阅读(118)  评论(0编辑  收藏  举报