-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMaximumBinaryTree.java
98 lines (93 loc) · 2.64 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*https://leetcode.com/problems/maximum-binary-tree/*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int n;
Map<Integer,Integer> hash;
public TreeNode constructMaximumBinaryTree(int[] nums) {
n = nums.length;
hash = new HashMap<Integer,Integer>();
int max = -1;
for (int i = 0; i < n; ++i)
{
hash.put(nums[i],i);
if (nums[i] > max) max = nums[i];
}
return buildTree(nums,hash.get(max),0,n-1);
}
private TreeNode buildTree(int[] nums, int index, int left, int right)
{
TreeNode root = new TreeNode(nums[index]);
int rightBorder = index-1, leftBorder = index+1;
if (rightBorder >= left)
{
int maxIndex = getMaxIndex(nums,left,rightBorder);
root.left = buildTree(nums,maxIndex,left,rightBorder);
}
if (leftBorder <= right)
{
int maxIndex = getMaxIndex(nums,leftBorder,right);
root.right = buildTree(nums,maxIndex,leftBorder,right);
}
return root;
}
private int getMaxIndex(int[] nums, int l, int r)
{
int max = nums[l], maxIndex = l;
for (int i = l; i <= r; ++i)
{
if (nums[i] > max)
{
max = nums[i];
maxIndex = i;
}
}
return maxIndex;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
TreeNode root = new TreeNode(Integer.MAX_VALUE);
helper(nums, root, 0);
return root.right;
}
private int helper(int[] nums, TreeNode root, int pos) {
while (pos > -1 && pos < nums.length) {
if (nums[pos] < root.val) {
TreeNode cur = new TreeNode(nums[pos]), right = root.right;
root.right = cur;
cur.left = right;
pos = helper(nums, cur, pos + 1);
} else return pos;
}
return -1;
}
}