653.最大二叉树

给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:

创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树

 

在分割数组的时候和中后序构造二叉树有所不同

该题是找最大值,需要遍历数组,因此需要重新定义变量

而上一题是找符合要求的值,for循环中不需要重新定义变量

class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        TreeNode* node= new TreeNode(0);
        if(nums.size()==1)//终止条件
        {
            node->val=nums[0];
            return node;
        }

        int maxvalue=0;
        int index=0;
        for(int i=0;i<nums.size();i++)// 找到数组中最大的值和对应的下标
        {
            if(nums[i]>maxvalue)
            {
                maxvalue=nums[i];
                index=i;
            }
        }

        node->val=maxvalue;

        if(index>0)//左子树
        {   
            vector<int> nec(nums.begin(),nums.begin()+index); //新数组取到原数组最大值的前一位
            node->left=constructMaximumBinaryTree(nec);
        }

        if(index< (nums.size()-1))//右子树
        {
            vector<int> nec(nums.begin()+ index + 1,nums.end());
            node->right=constructMaximumBinaryTree(nec);
        }

        return node;

    }
};

 

posted @ 2023-05-26 20:58  该说不唠  阅读(26)  评论(0)    收藏  举报