Leetcode | 103. Binary Tree Zigzag Level Order Traversal

题目:二叉树的锯齿形层次遍历

 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 public:
12     vector<vector<int>> zigzagLevelOrder(TreeNode* root) 
13     {
14         if(!root)
15             return vector<vector<int>>{};
16         vector<vector<int>> vec;    
17         queue<TreeNode*> qu;
18         qu.push(root);
19         int flag = 0;
20         while(!qu.empty())
21         {
22             flag++;
23              vector<int> temp;
24             int n = qu.size();
25             while(n--)
26             {
27                 TreeNode *p = qu.front();
28                 qu.pop();
29                 temp.push_back(p->val);
30                 if(p->left)
31                     qu.push(p->left);
32                 if(p->right)
33                     qu.push(p->right);      
34             }
35             if(flag % 2 == 0)
36                 reverse(temp.begin(), temp.end());
37             vec.push_back(temp);    
38         }
39         return vec;       
40     }
41 };

猜你喜欢

转载自www.cnblogs.com/sunbines/p/9669703.html
今日推荐