-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path654.txt
More file actions
40 lines (36 loc) · 955 Bytes
/
654.txt
File metadata and controls
40 lines (36 loc) · 955 Bytes
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
/**
* 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[] A) {
return dfs(A,0,A.length-1);
}
public TreeNode dfs(int A[],int l,int r){
if(l>r)return null;
if(l==r)return new TreeNode(A[l]);
int M=Integer.MIN_VALUE;
int index=0;
for(int i=l;i<=r;i++){
if(A[i]>M){
M=A[i];
index=i;
}
}
TreeNode node=new TreeNode(A[index]);
node.left=dfs(A,l,index-1);
node.right=dfs(A,index+1,r);
return node;
}
}