1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public TreeNode constructMaximumBinaryTree(int[] nums) {
return construct(nums, 0, nums.length - 1);
}
private TreeNode construct(int[] nums, int start, int end) {
if (start > end)
return null;
int index = -1;
int maxVal = Integer.MIN_VALUE;
for (int i = start; i <= end; i++) {
if (maxVal < nums[i]) {
index = i;
maxVal = nums[i];
}
}
TreeNode root = new TreeNode(maxVal);
root.left = construct(nums, start, index-1);
root.right = construct(nums, index+1, end);
return root;
}
|