Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
可以直接使用該題的代碼:http://www.reibang.com/p/e12727485829咧欣,然后將結(jié)果的數(shù)組反轉(zhuǎn)即可。
反轉(zhuǎn)數(shù)組比較慢轨帜,可以先得到數(shù)的高度魄咕,然后在遞歸處理的時(shí)候由數(shù)的層數(shù),就可以知道應(yīng)該放在數(shù)組哪個(gè)位置了蚌父。
/**
* 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** levelOrderBottom(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)/2;i++)
{
int temp;
if((*columnSizes)[i] > (*columnSizes)[(*returnSize)-1-i])
{
for(int j=0;j<(*columnSizes)[i];j++)
{
temp=ans[i][j];
ans[i][j]=ans[(*returnSize)-1-i][j];
ans[(*returnSize)-1-i][j]=temp;
}
}
else
{
printf("3\n");
for(int j=0;j<(*columnSizes)[(*returnSize)-1-i];j++)
{
temp=ans[i][j];
ans[i][j]=ans[(*returnSize)-1-i][j];
ans[(*returnSize)-1-i][j]=temp;
}
}
temp=(*columnSizes)[i];
(*columnSizes)[i]=(*columnSizes)[(*returnSize)-1-i];
(*columnSizes)[(*returnSize)-1-i]=temp;
}
return ans;
}