-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaximumBinaryTree.java
39 lines (31 loc) · 949 Bytes
/
MaximumBinaryTree.java
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
29
30
31
32
33
34
35
36
37
38
39
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
// https://leetcode.com/problems/maximum-binary-tree/
public class MaximumBinaryTree {
private final int[] input;
public MaximumBinaryTree(int[] input) {
this.input = input;
}
public TreeNode solution() {
return construct(input, 0, input.length);
}
private TreeNode construct(int[] nums, int l, int r) {
if (l == r) {
return null;
}
int max = max(nums, l, r);
TreeNode root = new TreeNode(nums[max]);
root.left = construct(nums, l, max);
root.right = construct(nums, max + 1, r);
return root;
}
private int max(int[] nums, int l, int r) {
int max = l;
for (int i = l; i < r; i++) {
if (nums[max] < nums[i]) {
max = i;
}
}
return max;
}
}