题目:
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] ]
代码如下:
void getleverorder(TreeNode *root,vector<vector<int> > &getnode,int i)
{
if(root!=NULL)
{
if(i>getnode.size())
{
vector<int> tmp;
tmp.push_back(root->val);
getnode.push_back(tmp);
}
else
{
getnode[i-1].push_back(root->val);
}
getleverorder(root->left,getnode,i+1);
getleverorder(root->right,getnode,i+1);
}
return;
}
void swap(vector<int> &tmp)
{
int n=tmp.size()-1,i=0;
while(i<n)
{
int t=tmp[i];
tmp[i++]=tmp[n];
tmp[n--]=t;
}
return;
}
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > getnode;
int i=1;
getleverorder(root,getnode,i);
for(int i=0;i<getnode.size();i++)
{
if(i%2==1)
{
swap(getnode[i]);
}
}
return getnode;
}