1、题目描述
2、分析
找出最大元素,然后分割数组调用。
3、代码
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
int size = nums.size();
if (size == )
return NULL;
TreeNode *dummy = new TreeNode();
maxcont(dummy->left, , size-, nums);
return dummy->left;
} void maxcont(TreeNode* &parent, int left, int right, vector<int>& nums)
{
if (left > right )
return ;
int maxindex = find_max(left, right, nums);
TreeNode *tmp = new TreeNode(nums[maxindex]);
parent = tmp;
maxcont(tmp->left, left, maxindex-, nums);
maxcont(tmp->right, maxindex + , right, nums);
} int find_max(int left, int right, vector<int> &nums)
{
int n = ;
int maxVal = INT_MIN;
for (int i = left; i <= right ; i++) {
if ( nums[i] > maxVal) {
maxVal = nums[i];
n = i;
} }
return n;
}