-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem654.java
More file actions
57 lines (47 loc) · 1.28 KB
/
Problem654.java
File metadata and controls
57 lines (47 loc) · 1.28 KB
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
package com.leetcode.problems;
//最大二叉树
import com.leetcode.datastructs.TreeNode;
class Solution654 {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if(nums==null||nums.length==0)
{
return null;
}
TreeNode root = treeBuild(nums, 0, nums.length-1);
return root;
}
public TreeNode treeBuild(int [] nums, int left, int right){
if(left==right)
{
return new TreeNode(nums[left]);
}
if(left>right)
{
return null;
}
int i = maxIndex(nums, left, right);
TreeNode root = new TreeNode(nums[i]);
root.left = treeBuild(nums, left, i-1);
root.right = treeBuild(nums,i+1, right);
return root;
}
public int maxIndex(int[] nums, int left,int right)
{
int index = left;
for (int i = left; i <= right; i++) {
if(nums[i]>nums[index])
{
index = i;
}
}
return index;
}
}
public class Problem654 {
public static void main(String[] args) {
int[] nums = {3,2,1,6,0,5};
Solution654 s = new Solution654();
TreeNode r = s.constructMaximumBinaryTree(nums);
System.out.println("hello");
}
}