题目:
给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:
二叉树的根是数组中的最大元素。
左子树是通过数组中最大值左边部分构造出的最大二叉树。
右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。
示例 :
输入:[3,2,1,6,0,5]
输出:返回下面这棵树的根节点:
6
/ \
3 5
\ /
2 0
\
1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-binary-tree
思路:
用递归的方式来做,我们先从给定的数组 nums 下标从i 到 j 中找到最大的元素值 max 与 其下标 maxIndex ,生成二叉树节点 TreeNode( max ) ,并把数组分成 [i , maxIndex-1] 与 [maxIndex + 1, j] ,分别从两个子数组中找到左子节点与右子节点。依次类推。 递归终止条件为 i > maxIndex - 1 或者 j < maxIndex + 1
java代码如下
publis class Main{
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructItoJ(nums,0,nums.length-1);
}
public TreeNode constructItoJ(int[] nums,int i,int j){
//递归终止条件
if(i>j){
return null;
}
int maxIndex = i;
int index = i;
int max = nums[i];
for(;index<=j;index++){
if(max<nums[index]){
max = nums[index];
maxIndex = index;
}
}
TreeNode root = new TreeNode(max);
TreeNode left = constructItoJ(nums,i,maxIndex-1);
TreeNode right = constructItoJ(nums,maxIndex+1,j);
root.left = left;
root.right = right;
return root;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}