/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int>> result; vector<int> vec; result.clear(); if(NULL==root) return result; deque<TreeNode*>deq; deq.clear(); deq.push_back(root); int len1 = 1; int len2 ; bool dir = true; while(!deq.empty()) { len2 = 0; if(dir) { while(len1--) { vec.push_back(deq.front()->val); if(deq.front()->left!=NULL) { deq.push_back(deq.front()->left); len2++; } if(deq.front()->right!=NULL) { deq.push_back(deq.front()->right); len2++; } deq.pop_front(); } dir = !dir; } else { while(len1--) { vec.push_back(deq.back()->val); if(deq.back()->right!=NULL) { deq.push_front(deq.back()->right); len2++; } if(deq.back()->left!=NULL) { deq.push_front(deq.back()->left); len2++; } deq.pop_back(); } dir = !dir; } result.push_back(vec); len1=len2; vec.clear(); } return result; } };
1. 双端队列完成
2. 记住clear()