654.最大二叉树

在这里插入图片描述
思路:
这是一道典型的运用分治法的题目
1.首先在数组中找到最大值,以该最大值构建最大二叉树,以该最大值的下标为界,将数组划分为两个数组。
2.以第一个数组构建最大二叉树,作为根节点的左子树。
3.以第二个数组构建最大二叉树,作为根节点的右子树。
4.重复以上操作,当begin>end,此时数组为空,返回NULL,当begin==end,此时数组只有一个元素,直接以该元素构建子树。
5.最后返回根节点

/**
 * 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* myconstructMaximumBinaryTree(int arr[],int begin,int end)
    {
        if(begin==end) return new TreeNode(arr[end]);
        if(begin>end) return NULL;
        int max=-100,maxpos=-1;
        for(int i=begin;i<=end;i++)
        {
            if(arr[i]>=max)
            {
                max=arr[i];
                maxpos=i;
            }
        }
        TreeNode* root= new TreeNode(max);
        root->left=myconstructMaximumBinaryTree(arr,begin,maxpos-1);
        root->right=myconstructMaximumBinaryTree(arr,maxpos+1,end);
        return root;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        if(nums.empty()) return NULL;
        int arr[1000],i=0;
    for(auto c:nums)
        arr[i++]=c;
        return myconstructMaximumBinaryTree(arr,0,i-1);
    }
};

在这里插入图片描述

发布了90 篇原创文章 · 获赞 7 · 访问量 2189

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/102599072