有错误
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return build(nums,0,nums.size()-1);
}
int find_index(vector<int>& nums,int l,int r){
int Max = 1000001,max_index = l;
for(int i = l ;i <= r; i++){
if(Max < nums[i]){
Max = nums[i];
max_index = i;
}
}
return max_index;
}
TreeNode *build(vector<int>& nums,int l,int r){
if(l >= r) return NULL;
int bond = find_index(nums,l,r);
TreeNode *root = new TreeNode(nums[bond]);
root->left = build(nums,l,bond-1);
root->right = build(nums,bond+1,r);
return root;
}
};
迭代器版本,无错误
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums.begin(),nums.end());
}
TreeNode *construct(vector<int>::iterator l ,vector<int>::iterator r){
if(l==r) return nullptr;
auto it = max_element(l,r);
TreeNode *tn = new TreeNode(*it);
tn->left = construct(l,it);//这两个参数是左闭右开的,和使用迭代器的习惯类似
tn->right = construct(it+1,r);
return tn;
}
};