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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
运用递归的思路,采用上题的算法:http://www.jianshu.com/p/e12727485829,最后将结果根据树的高度的奇偶性,进行数组翻转即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
void level(struct TreeNode* root, int** columnSizes, int* returnSize,int** ans,int height)
{
if(height>*returnSize)
{
*returnSize=*returnSize+1;
ans[height-1]=(int *)malloc(sizeof(int)*100000);
(*columnSizes)[height-1]=0;
}
if(root==NULL)return;
ans[height-1][(*columnSizes)[height-1]]=root->val;
//printf("%d: %d %d\n",height-1,(*columnSizes)[height-1],ans[height-1][(*columnSizes)[height-1]]);
(*columnSizes)[height-1]=(*columnSizes)[height-1]+1;
if(root->left!=NULL)
level(root->left,columnSizes,returnSize,ans,height+1);
if(root->right!=NULL)
level(root->right,columnSizes,returnSize,ans,height+1);
return;
}
int** zigzagLevelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {
int **ans=(int**)malloc(sizeof(int*)*1000);
*returnSize=0;
*columnSizes=(int *)malloc(sizeof(int)*1000);
if(root==NULL)return ans;
level(root,columnSizes,returnSize,ans,1);
for(int i=0;i<(*returnSize);i++)
{
if(i%2==1)
{
for(int j=0;j<(*columnSizes)[i]/2;j++)
{
int temp=ans[i][j];
ans[i][j]=ans[i][ (*columnSizes)[i]-1-j ];
ans[i][ (*columnSizes)[i]-1-j ]=temp;
}
}
}
return ans;
}