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] ]
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
queue<TreeNode *> nextLevel;
queue<TreeNode *> curLevel;
TreeNode *r = root;
vector<vector<int> > ret;
if (r==NULL)
return ret;
curLevel.push(r);
bool l2r=true;
while(1)
{
vector<int> tmpV;
while(!curLevel.empty())
{
TreeNode *tmp=curLevel.front();
if (tmp!=NULL)
{
tmpV.push_back(tmp->val);
if (tmp->left)
nextLevel.push(tmp->left);
if (tmp->right)
nextLevel.push(tmp->right);
}
curLevel.pop();
}
if (!l2r)
reverse(tmpV.begin(),tmpV.end());
l2r=!l2r;
ret.push_back(tmpV);
if (nextLevel.empty())
break;
else
{
curLevel.swap(nextLevel);
}
}
return ret;
}
No comments:
Post a Comment