Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*这个题目我还是采用了一直使用的两个stack(如果是层次的话就用两个queue)来处理,比较直观。需要注意的是,当处理下一层是,要分层次的奇偶,来判断是先压入左孩子,还是先压入右孩子*/
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> re;
if(root==NULL) return re;
stack<TreeNode *> q;
stack<TreeNode *> s;
q.push(root);
while(!q.empty()||!s.empty()){
vector<int> temp;
if(!q.empty()){
while(!q.empty()){
TreeNode * cur=q.top();
temp.push_back(cur->val);
if(cur->left!=NULL) s.push(cur->left);
if(cur->right!=NULL) s.push(cur->right);
q.pop();
}
re.push_back(temp);
continue;
}
if(!s.empty()){
while(!s.empty()){
TreeNode * cur=s.top();
temp.push_back(cur->val);
if(cur->right!=NULL) q.push(cur->right);
if(cur->left!=NULL) q.push(cur->left);
s.pop();
}
re.push_back(temp);
}
}
return re;
}
};