654. Maximum Binary Tree

来源:互联网 发布:国人欣赏水平 知乎 编辑:程序博客网 时间:2024/06/06 13:08
  • Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
  1. The root is the maximum number in the array. The left subtree is the
    maximum tree constructed from left part subarray divided by the
    maximum number.
  2. The right subtree is the maximum tree constructed from right part
    subarray divided by the maximum number.
  3. Construct the maximum tree by the given array and output the root
    node of this tree.
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) {    int i = 0;    int max = 0;    struct TreeNode * root = NULL;    if(numsSize <= 0){        return NULL;    }    max = 0;    for(i = 1;i < numsSize; ++i){        if(nums[i]>nums[max]){            max = i;        }    }    root = (struct TreeNode *)malloc(sizeof(struct TreeNode));    root->val = nums[max];    root->left = constructMaximumBinaryTree(nums,max);    root->right = constructMaximumBinaryTree(nums+max+1,numsSize - max -1);    return root;}
原创粉丝点击