Skip to content

654. Maximum Binary Tree

难度: Medium

刷题内容

原题连接 * https://leetcode-cn.com/problems/maximum-binary-tree/

内容描述 ``` 给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

二叉树的根是数组中的最大元素。 左子树是通过数组中最大值左边部分构造出的最大二叉树。 右子树是通过数组中最大值右边部分构造出的最大二叉树。 通过给定的数组构建最大二叉树,并且输出这个树的根节点。

Example 1:

输入: [3,2,1,6,0,5] 输入: 返回下面这棵树的根节点:

  6
/   \

3 5 \ / 2 0
\ 1 ```

解题方案

思路 1

深搜构建二叉树
TreeNode* dfs(vector<int>& nums, int start, int end){
    int root_val = 0, max=INT_MIN;
    if(start==end)
        return NULL;
    for(int i=start;i<end;i++){
        if(max<nums[i]){
            max = nums[i];
            root_val = i;
        }
    } 
    TreeNode* root = new TreeNode(max);
    root->left = dfs(nums, start, root_val);
    root->right = dfs(nums, root_val+1, end);
    return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    return dfs(nums, 0, nums.size());
}


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组