LeetCode——最大二叉树

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

  • 二叉树的根是数组中的最大元素。
  • 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  • 右子树是通过数组中最大值右边部分构造出的最大二叉树。

通过给定的数组构建最大二叉树,并且输出这个树的根节点。

A:树的递归

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums.length == 0)
            return null;
        int max = nums[0];
        int maxIndex = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > max) {
                max = nums[i];
                maxIndex = i;
            }
        }
        TreeNode node = new TreeNode(max);
        int[] left = Arrays.copyOfRange(nums, 0, maxIndex);
        node.left = constructMaximumBinaryTree(left);
        int[] right = Arrays.copyOfRange(nums, maxIndex + 1, nums.length);
        node.right = constructMaximumBinaryTree(right);
        return node;
    }
原文地址:https://www.cnblogs.com/xym4869/p/13416454.html