103. 二叉树的锯齿形层次遍历

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution 
11 {
12     vector<vector<int>> ans;
13 public:
14     vector<vector<int>> zigzagLevelOrder(TreeNode* root) 
15     {
16         if(!root) return ans;
17         queue<TreeNode*> q;
18         q.push(root);
19         while(!q.empty())
20         {
21             int n = q.size();
22             vector<int> temp;
23             for(int i = 0;i < n;i ++)
24             {
25                 TreeNode* t = q.front();
26                 q.pop();
27                 temp.push_back(t->val);
28                 if(t->left) q.push(t->left);
29                 if(t->right) q.push(t->right);
30             }
31             if(ans.size() % 2) reverse(temp.begin(),temp.end());
32             ans.push_back(temp);
33         }
34         return ans;
35     }
36 };

 

posted @ 2020-04-01 13:05  Jinxiaobo0509  阅读(119)  评论(0)    收藏  举报