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:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > result;
if(!root)
return result;
stack<TreeNode*> s1,s2,s3;
s1.push(root);
TreeNode *tmp;
int level =0;
while(!s1.empty())
{
tmp = s1.top();
if(result.size()==level)
{
vector<int> tmpvec;
tmpvec.push_back(tmp->val);
result.push_back(tmpvec);
}
else
result[level].push_back(tmp->val);
s1.pop();
if(level%2==0) //odd level
{
if(tmp->left)
s2.push(tmp->left);
if(tmp->right)
s2.push(tmp->right);
}
else //even level
{
if(tmp->right)
s2.push(tmp->right);
if(tmp->left)
s2.push(tmp->left);
}
if(s1.empty()) //after one level
{
s1 = s2;
s2 = s3;
level++;
}
}
return result;
}
No comments:
Post a Comment