[Problem]
[Solution]
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] ]
[Solution]
/**说明:版权所有,转载请注明出处。 Coder007的博客
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
// null subtree
if(root == NULL){
return res;
}
// initial
vector<TreeNode*> head;
head.push_back(root);
stack<vector<TreeNode*> > myStack;
myStack.push(head);
// level order traversal
int level = 0;
while(!myStack.empty()){
vector<TreeNode*> nodes = myStack.top();
myStack.pop();
// visit children
vector<int> tmpRes;
vector<TreeNode*> children;
for(int i = 0; i < nodes.size(); ++i){
if(level%2 == 0){
tmpRes.push_back(nodes[i]->val);
}
else{
tmpRes.insert(tmpRes.begin(), nodes[i]->val);
}
// visit the left child
if(nodes[i]->left != NULL){
children.push_back(nodes[i]->left);
}
// visit the right child
if(nodes[i]->right != NULL){
children.push_back(nodes[i]->right);
}
}
// add
if(children.size() > 0){
myStack.push(children);
}
if(tmpRes.size() > 0){
res.push_back(tmpRes);
}
level++;
}
return res;
}
};