-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaximumBinaryTree.java
49 lines (41 loc) · 1.05 KB
/
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
40
41
42
43
44
45
46
47
48
49
package binarytree;
import binarytree.BinaryTreeTest.TreeNode;
/**
* @author Shogo Akiyama
* Solved on 09/30/2019
*
* 654. Maximum Binary Tree
* https://leetcode.com/problems/maximum-binary-tree/
* Difficulty: Medium
*
* Approach: Recursion
* Runtime: 2 ms, faster than 99.65% of Java online submissions for Maximum Binary Tree.
* Memory Usage: 38.2 MB, less than 97.83% of Java online submissions for Maximum Binary Tree.
*
* @see BinaryTreeTest#testMaximumBinaryTree()
*/
public class MaximumBinaryTree {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return recurse(nums, 0, nums.length - 1);
}
private TreeNode recurse(int[] nums, int s, int e) {
if (s > e) {
return null;
}
if (s == e) {
return new TreeNode(nums[s]);
}
int max = nums[s];
int index = s;
for (int i = s + 1; i <= e; i++) {
if (nums[i] > max) {
max = nums[i];
index = i;
}
}
TreeNode node = new TreeNode(nums[index]);
node.left = recurse(nums, s, index - 1);
node.right = recurse(nums, index + 1, e);
return node;
}
}