LeetCode 654. 最大二叉树

题目链接:https://leetcode-cn.com/problems/maximum-binary-tree/

给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

二叉树的根是数组中的最大元素。
左子树是通过数组中最大值左边部分构造出的最大二叉树。
右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。

 

示例 :

输入:[3,2,1,6,0,5]
输出:返回下面这棵树的根节点:

6
/ \
3 5
\ /
2 0
\
1
 

提示:

给定的数组的大小在 [1, 1000] 之间。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize){
10     if(numsSize==0) return NULL;
11     struct TreeNode *head=(struct TreeNode*)malloc(sizeof(struct TreeNode));
12     int index=0;
13     for(int i=1;i<numsSize;i++){
14         if(nums[i]>nums[index]) index=i;
15     }
16     head->val=nums[index];
17     head->right=constructMaximumBinaryTree(nums+index+1,numsSize-index-1);
18     head->left=constructMaximumBinaryTree(nums,index);
19     return head;
20 }

 

posted @ 2019-08-16 14:15  wydxry  阅读(316)  评论(0编辑  收藏  举报
Live2D