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);
}
结果:

浙公网安备 33010602011771号