LeetCode - 654.Maximum Binary Tree
题目链接 https://leetcode.com/problems/maximum-binary-tree/description/
题目分析
题目给出一个不重复的数组, 根据规则生成一个二叉树
- 根节点是数组最大值
- 左孩子是数组最大值左侧的最大值
- 右孩子是数组最大值右侧的最大值
从题目来看有一种递归的感觉, 然后再加上二分查找.
在做的过程中主要遇到了两个问题
- 在二分查找过程中, 分为的两个区域应该是 [low, mid), [mid + 1, high) 如果处理的不正确就可能导致递归出错
- 在编写获取数组最大值的方法的时候, 没有考虑清楚方法返回的是最大值的 value 还是最大值的 index. 导致出问题
下面附上个人的代码
public TreeNode constructMaximumBinaryTree(int[] nums) {
if(nums.length <=0)
return null;
int max = getMax(nums, 0, nums.length);
TreeNode root = new TreeNode(nums[max]);
root.right = func(nums, max + 1, nums.length);
root.left = func(nums, 0, max);
return root;
}
TreeNode func(int[] nums, int low, int high){
if(low >= high){
return null;
}else{
int max = getMax(nums, low, high);
TreeNode root = new TreeNode(nums[max]);
root.right = func(nums, max + 1, high);
root.left = func(nums, low, max);
return root;
}
}
int getMax(int[] nums, int low, int high){
if(low >=high)
return -1;
int max = low;
for(int i = low; i < high ; i ++){
if(nums[i] > nums[max]){
max = i;
}
}
return max;
}
需要注意
- 表示最小值的是Integer.MIN_VALUE