领扣LintCode算法问题答案-1106. 最大二叉树

领扣LintCode算法问题答案-1106. 最大二叉树

1106. 最大二叉树

描述

给定一个没有重复元素的整数数组。根据此数组构建的最大二叉树定义如下:

  • root是数组中的最大数字。
  • 左子树是根据最大数字左侧的子数组构建的最大二叉树。
  • 右子树是根据最大数字右侧的子数组构建的最大二叉树。

通过给定的数组构造最大二叉树并返回此树的根节点。

给定的数组的大小范围为 [1,1000]。

样例 1:

输入: {3,2,1,6,0,5}
输出: 返回代表下面这棵树的根节点:
     6
   /   \
  3     5
   \   / 
    2 0   
     \
      1

样例 2:

输入: {1,2,3,4}
输出: 返回代表下面这棵树的根节点:
        4
       /
      3
     /
    2
   /
  1    

题解

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param nums: an array
     * @return: the maximum tree
     */
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        // Write your code here
        TreeNode root = constructMaximumBinaryTree(nums, 0, nums.length - 1);
        return root;
    }

    private TreeNode constructMaximumBinaryTree(int[] nums, int startIndex, int endIndex) {
        // Write your code here
        if (endIndex < startIndex) {
            return null;
        }
        int maxIndex = startIndex;
        for (int i = startIndex + 1; i <= endIndex; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(nums[maxIndex]);
        root.left = constructMaximumBinaryTree(nums, startIndex, maxIndex - 1);
        root.right = constructMaximumBinaryTree(nums, maxIndex + 1, endIndex);
        return root;
    }
}

原题链接点这里

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二当家的白帽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值