leetcode[107]:Binary Tree Level Order Traversal II

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 基础上修改下标。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值