-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprblm1008.java
More file actions
35 lines (30 loc) · 899 Bytes
/
prblm1008.java
File metadata and controls
35 lines (30 loc) · 899 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
public class prblm1008 {
public static void main(String[] args) {
int[] preorder = {8,5,1,7,10,12};
TreeNode ans = new prblm1008().bstFromPreorder(preorder);
new prblm1008().preOrder(ans);
}
public TreeNode bstFromPreorder(int[] preorder) {
TreeNode root = null;
for(int val : preorder){
root = makeBST(root, val);
}
return root;
}
private TreeNode makeBST(TreeNode root, int val){
if(root == null) return new TreeNode(val);
if(val < root.val){
root.left = makeBST(root.left, val);
}
else{
root.right = makeBST(root.right, val);
}
return root;
}
private void preOrder(TreeNode root){
if(root == null) return;
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
}