/**
* 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());
}
TreeNode* build(vector<int>& nums, int left, int right){
if(left>=right) return nullptr;
int max_index = left;
for(int i = left; i <right; i++){
if(nums[i] > nums[max_index]){
max_index = i;
}
}
TreeNode* node = new TreeNode(nums[max_index]);
node->left = build(nums, left, max_index);
node->right = build(nums, max_index+1, right);
return node;
}
};
今天除了这道题,还把昨天的题目优化了一下,感觉还是不错的哦。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)