forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumBinaryTree.java
More file actions
25 lines (23 loc) · 754 Bytes
/
MaximumBinaryTree.java
File metadata and controls
25 lines (23 loc) · 754 Bytes
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 class MaximumBinaryTree {
/**
* 复杂度平均O(nlgn),最差O(n^2)
*/
public TreeNode constructMaximumBinaryTree(int[] nums, int start, int end) {
if (start > end) {
return null;
}
int max = start;
for (int i = start + 1; i <= end; i++) {
if (nums[i] > nums[max]) {
max = i;
}
}
TreeNode root = new TreeNode(nums[max]);
root.left = constructMaximumBinaryTree(nums, start, max - 1);
root.right = constructMaximumBinaryTree(nums, max + 1, end);
return root;
}
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree(nums, 0, nums.length - 1);
}
}