/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums,0,nums.size());
}
//根据区间范围递归的定义并创建最大二叉树 左闭右开区间
TreeNode* construct(vector<int>&nums,int left,int right)
{
if(left==right)
{
return nullptr;//这里使用了智能指针
}
int index=findMax(nums,left,right);
TreeNode* root=new TreeNode(nums[index]);
root->left=construct(nums,left,index);
root->right=construct(nums,index+1,right);//这里要维护住left,right的语义
return root;
}
//在左闭右开区间寻找最大值的下标
int findMax(vector<int>&nums,int left,int right)
{
int maxIndex=left;
for(int i=left;i<right;i++)
{
if(nums[i]>nums[maxIndex])
{
maxIndex=i;
}
}
return maxIndex;
}
};
Leetcode:654.最大二叉树
最新推荐文章于 2022-03-24 00:00:00 发布
本文介绍了一种构建最大二叉树的方法,通过递归在给定的整数数组中找到最大值作为根节点,然后递归地构建左右子树。这种方法确保了每个子树的根节点都是其对应子数组中的最大值。
209

被折叠的 条评论
为什么被折叠?



