题目
给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:
二叉树的根是数组中的最大元素。
左子树是通过数组中最大值左边部分构造出的最大二叉树。
右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。
示例 :
思路
构造树一般是先序遍历,因为先构造中间节点(根节点),然后递归构造左子树和右子树
递归三部曲:
- 找终止条件:当
l>r
时,说明数组中已经没元素了,自然当前返回的节点为null
。 - 每一级递归返回的信息是什么:返回的应该是当前已经构造好了最大二叉树的
root
节点。 - 一次递归做了什么:找当前范围为
[l,r]
的数组中的最大值作为root
节点,然后将数组划分成[l,maxIndex-1]
和[maxIndex+1,r]
两段,并分别构造成root
的左右两棵子最大二叉树。
java代码如下:
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return maxTree(nums, 0, nums.length - 1);
}
public TreeNode maxTree(int[] nums, int l, int r){
if(l > r){//说明数组没有元素了
return null;
}
int maxIndex = findMax(nums, l, r);//maxIndex为当前数组中最大值的索引
TreeNode root = new TreeNode(nums[maxIndex]);//将数组最大值赋给根节点
root.left = maxTree(nums, l, maxIndex - 1);
root.right = maxTree(nums, maxIndex + 1, r);
return root;
}
//找最大值的索引
public int findMax(int[] nums, int l, int r){
int max = Integer.MIN_VALUE, maxIndex = l;
for(int i = l; i <= r; i++){
if(max < nums[i]){
max = nums[i];
maxIndex = i;
}
}
return maxIndex;
}
}