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 vector<int> row; 14 vector<vector<int>> v; 15 queue<TreeNode *> q; 16 if(root == NULL) 17 return v; 18 q.push(root); 19 TreeNode *temp; 20 int lev = 0; 21 while(!q.empty()) { 22 int size = q.size(); 23 while(size--) { 24 temp = q.front(); 25 q.pop(); 26 row.push_back(temp->val); 27 if(temp->left != NULL) { 28 q.push(temp->left); 29 } 30 if(temp->right != NULL) { 31 q.push(temp->right); 32 } 33 } 34 if(lev % 2) { 35 int n = row.size(); 36 for(int i = 0; i < n/2; i++) { 37 swap(row[i], row[n-i-1]); 38 } 39 } 40 v.push_back(row); 41 lev++; 42 row.clear(); 43 } 44 return v; 45 } 46 };
相关文章: