Skip to content

Commit af8c5ea

Browse files
authored
day24
1 parent 89e03ac commit af8c5ea

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
public TreeNode bstFromPreorder(int[] preorder) {
12+
return construct(preorder,0,preorder.length-1);
13+
}
14+
15+
public TreeNode construct(int[] pre,int start,int end){
16+
if(start>end) return null;
17+
18+
TreeNode root=new TreeNode(pre[start]);
19+
20+
int val=-1;
21+
for(int i=start+1;i<=end;i++){
22+
if(pre[i]>pre[start]){
23+
val=i;
24+
break;
25+
}
26+
}
27+
28+
if(val==-1)
29+
val=end+1;
30+
root.left=construct(pre,start+1,val-1);
31+
root.right=construct(pre,val,end);
32+
33+
return root;
34+
}
35+
}

0 commit comments

Comments
 (0)