llllmz

导航

654. 最大二叉树c

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxindex(int* nums,int head,int tail){
    if(head==tail) return head;
    int max=head;
    for(int i=head;i<=tail;i++){
        if(nums[i]>nums[max]) max=i;
    }
    return max;
}

struct TreeNode* build(int*nums,int head,int tail){
    if(head>tail) return NULL;
    int max=maxindex(nums,head,tail);
    struct TreeNode* root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->val=nums[max];
    root->left=build(nums,head,max-1);
    root->right=build(nums,max+1,tail);
    return root;
}

struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) {
    if(numsSize<=0) return NULL;
    return build(nums,0,numsSize-1);
}

结果:

posted on 2024-03-06 13:19  神奇的萝卜丝  阅读(15)  评论(0)    收藏  举报