- Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
- 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. - The right subtree is the maximum tree constructed from right part
subarray divided by the maximum number. - Construct the maximum tree by the given array and output the root
node of this tree.
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;
}