1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public TreeNode constructMaximumBinaryTree(int[] nums) {
return buildTree(nums, 0, nums.length - 1);
}
public TreeNode buildTree(int[] nums, int start, int end) {
if (start > end) {
return null;
}
int maxIndex = getMaxIndex(nums, start, end);
TreeNode root = new TreeNode(nums[maxIndex]);
root.left = buildTree(nums, start, maxIndex - 1);
root.right = buildTree(nums, maxIndex + 1, end);
return root;
}
//获取从 start到end之间最大值的下标
public int getMaxIndex(int[] array, int start, int end) {
int maxIndex = start;
for (int i = start; i <= end; i++) {
if (array[i] > array[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
|