原题如下:
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] ]这道题的思路还是挺明确的,普通的层次遍历需要借助队列,而此题需要借助栈,(队列由于是先进先出,所以仅用一个就够了,但栈需要两个)另外由于方向不同,所以还需要一个标志位标记是先入左子树还是先入右子树。
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>>vv;
if(root == NULL)
return vv;
stack<TreeNode *> s1;
vector<int>v;
s1.push(root);
int flag = 0;
while(!s1.empty()){
stack<TreeNode *> s2;
while(!s1.empty()){
TreeNode * cur = s1.top();
v.push_back(cur->val);
s1.pop();
if(flag == 0){ //先左子树后右子树
if(cur->left != NULL)
s2.push(cur->left);
if(cur->right != NULL)
s2.push(cur->right);
}
else{
if(cur->right != NULL)
s2.push(cur->right);
if(cur->left != NULL)
s2.push(cur->left);
}
}
vv.push_back(v);
v.clear();
s1 = s2;
if(flag == 0)
flag = 1;
else
flag = 0;
}
return vv;
}
};