Skip to content

Commit c537a4e

Browse files
committed
Leetcode 654 MaximumBinaryTree
1 parent 9c6ca27 commit c537a4e

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public TreeNode constructMaximumBinaryTree(int[] nums) {
3+
return build(nums, 0, nums.length-1);
4+
}
5+
6+
private TreeNode build(int[] nums, int l , int r) {
7+
if(l > r) return null;
8+
int maxIndex = max(nums, l , r);
9+
TreeNode root = new TreeNode(nums[maxIndex]);
10+
root.left = build(nums, l, maxIndex-1);
11+
root.right = build(nums, maxIndex+1, r);
12+
return root;
13+
}
14+
15+
private int max(int[] nums, int l , int r) {
16+
int max = l;
17+
for(int i=l+1;i<=r;i++) {
18+
if(nums[max] < nums[i]) max = i;
19+
}
20+
21+
return max;
22+
}

0 commit comments

Comments
 (0)