654. 最大二叉树
左闭右开,当左右指针相同时就终止递归
class Solution {
public:
unordered_map<int,int> map;
int getmax(int left,int right,vector<int> & nums)
{
int m = INT_MIN;
for(int i=left;i<right;i++)
{
if(nums[i]>m)m=nums[i];
}
return m;
}
TreeNode* traversal(int left, int right, vector<int>& nums)
{
if(left>=right)return NULL;
int maxValue = getmax(left,right,nums);
TreeNode* root = new TreeNode(maxValue);
int maxIndex = map[maxValue];
root->left = traversal(left,maxIndex,nums);
root->right = traversal(maxIndex+1,right,nums);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if(nums.size()==0) return NULL;
for(int i=0;i<nums.size();i++)
map[nums[i]] = i;
return traversal(0,nums.size(), nums);
}
};