Maximum Binary Tree LeetCode solution in Java

1
class Solution {
2
public TreeNode constructMaximumBinaryTree(int[] nums) {
3
TreeNode root = construct(nums, 0, nums.length - 1);
4
return root;
5
}
6

7
private TreeNode construct(int[] nums, int start, int end) {
8
if (start > end) return null;
9
if (start == end) return new TreeNode(nums[start]);
10

11
int maxIdx = findMax(nums, start, end);
12
TreeNode root = new TreeNode(nums[maxIdx]);
13

14
root.left = construct(nums, start, maxIdx - 1);
15
root.right = construct(nums, maxIdx + 1, end);
16

17
return root;
18
}
19

20
private int findMax(int[] arr, int low, int high) {
21
int idx = -1, max = Integer.MIN_VALUE;
22
for (int i = low; i <= high; ++i)
23
if (arr[i] > max) {
24
max = arr[i];
25
idx = i;
26
}
27
return idx;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0