您的位置:首页 > 其它

leetcode[107]:Binary Tree Level Order Traversal II

2015-07-20 14:37 489 查看
Binary Tree Level Order Traversal II

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,#,#,15,7},

3
/ \
9  20
/  \
15   7


return its bottom-up level order traversal as:

[
[15,7],
[9,20],
[3]
]


/**
* 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().
*/
int maxDepth(struct TreeNode* root) {

int i, j;

i=j=1;

if(!root) return 0;
if(root->left) i += maxDepth(root->left);
if(root->right) j += maxDepth(root->right);

if( i > j ) return i;

return j;

}

int** levelOrderBottom(struct TreeNode* root, int** columnSizes, int* returnSize) {

int res[1000][1000];
int size[1000];
struct TreeNode stack[10000];
int i,ress,j,k,l,ll;
int **result;

l=maxDepth(root);

if(!root) return NULL;
result= (int**)malloc(sizeof(int*)*l);
*columnSizes = (int*)malloc(sizeof(int*)*l);
*returnSize = l;
i=j=k=0;
stack[0] = *root;
size[l-1]=1;
ll=1;
ress=1;
while(ll!=0)
{
ll=0;
printf("%d",l-i-1);
result[l-i-1] = (int*)malloc(sizeof(int*)*size[l-i-1]);

for(j=0;j<size[l-i-1];j++)
{
result[l-i-1][j]=stack[k+j].val;

if(stack[k+j].left) {ll++;stack[ress++]=*stack[k+j].left; }
if(stack[k+j].right) {ll++;stack[ress++]=*stack[k+j].right;}
}
k += j;
(*columnSizes)[l-i-1]=size[l-i-1];
i++;
size[l-i-1]=ll;
}
return result;

}


Binary Tree Level Order Traversal 基础上修改下标。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binary tree