-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathConstructMaximumBinaryTree.java
49 lines (42 loc) · 1.32 KB
/
ConstructMaximumBinaryTree.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums)
{
//Recursive helper function
return helper(nums,0,nums.length-1);
}
public TreeNode helper(int [] nums, int low, int high)
{
if(high < low)
return null;
//Identify the maximum element's index
int maxIndex = getMaxIndex(nums, low, high);
//Construct the root node
TreeNode root = new TreeNode(nums[maxIndex]);
//Generate the left sub tree from the left part of sub array
root.left = helper(nums,low, maxIndex-1);
//Generate the right sub tree from the right part of sub array
root.right = helper(nums, maxIndex+1, high);
//Return the root
return root;
}
public int getMaxIndex(int [] nums, int low, int high)
{
//Identify the maximum element's index to construct the root element
int maxIndex = low;
for(int i = low+1; i <= high; i++)
{
if(nums[i] > nums[maxIndex])
maxIndex = i;
}
return maxIndex;
}
}