-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
28 lines (25 loc) · 748 Bytes
/
Solution.java
File metadata and controls
28 lines (25 loc) · 748 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
26
27
28
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return build(nums, 0, nums.length - 1);
}
public TreeNode build(int[] nums, int beg, int end) {
if (beg > end) return null;
int maxIndex = beg;
for (int i = beg; i <= end; i++) {
if (nums[i] > nums[maxIndex]) maxIndex = i;
}
TreeNode root = new TreeNode(nums[maxIndex]);
root.left = build(nums, beg, maxIndex - 1);
root.right = build(nums, maxIndex + 1, end);
return root;
}
}