美文网首页
Leetcode 107. Binary Tree Level

Leetcode 107. Binary Tree Level

作者: persistent100 | 来源:发表于2017-08-17 22:17 被阅读0次

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.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** 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;
}

相关文章

网友评论

      本文标题:Leetcode 107. Binary Tree Level

      本文链接:https://www.haomeiwen.com/subject/rzznrxtx.html