训练营第二十天(二叉树 part06)
654.最大二叉树
题目
给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:
- 二叉树的根是数组中的最大元素。
- 左子树是通过数组中最大值左边部分构造出的最大二叉树。
- 右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。
示例 :
提示:
给定的数组的大小在 [1, 1000] 之间。
解答
方法一:
每次传入的参数是新的数组
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums.length == 0){
return null;
}
int max = Integer.MIN_VALUE;
int index = -1;
for (int i = 0; i < nums.length; i++) {
if (max < nums[i]){
index = i;
max = nums[i];
}
}
TreeNode root = new TreeNode(nums[index]);
int[] left = Arrays.copyOfRange(nums,0,index);
int[] right = Arrays.copyOfRange(nums,index + 1,nums.length);
root.left = constructMaximumBinaryTree(left);
root.right = constructMaximumBinaryTree(right);
return root;
}
}
方法二:
不改变数组,每次根据传入的索引来确定新的数组
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree1(nums, 0, nums.length)