-
Notifications
You must be signed in to change notification settings - Fork 0
/
a_164_Array_BST.java
53 lines (42 loc) · 1.22 KB
/
a_164_Array_BST.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
50
51
52
53
public class a_164_Array_BST {
static class Node{
int data ;
Node left;
Node right ;
Node(int data){
this.data = data ;
this.left = this.right = null ;
}
}
public static void preorder(Node root){
if(root == null){
return ;
}
System.out.print(root.data +" ");
preorder(root.left);
preorder(root.right);
}
public static Node createBST(int arr[], int si, int end){
if(si > end ){
return null ;
}
int mid = (si+end )/2 ;
Node root = new Node(arr[mid]) ;
root.left = createBST(arr, si, mid-1) ;
root.right = createBST(arr, mid+1, end) ;
return root ;
}
public static void main(String[] args) {
int arr[] = {3, 5, 6, 8, 10, 11, 12} ;
/*
* 8
* / \
* 5 11
* / \ / \
* 3 6 10 12
* Expected BST
*/
Node root = createBST(arr, 0, arr.length-1) ;
preorder(root);
}
}