LeetCode题解Maximum Binary Tree

1、题目描述

LeetCode题解Maximum Binary Tree

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;
}
上一篇:21.左旋转字符串[LeftRotateString]


下一篇:leetcode题解:Construct Binary Tree from Preorder and Inorder Traversal (根据前序和中序遍历构造二叉树)