-
Notifications
You must be signed in to change notification settings - Fork 1
/
ArrayToBST.java
48 lines (42 loc) · 1.1 KB
/
ArrayToBST.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
public class ArrayToBST {
static class Node {
int data;
Node left;
Node right;
public 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 convertToBST(int arr[], int st, int end) {
if(st > end) {
return null;
}
int mid = (st+end)/2;
Node curr = new Node(arr[mid]);
curr.left = convertToBST(arr, st, mid-1);
curr.right = convertToBST(arr, mid+1, end);
return curr;
}
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 = convertToBST(arr, 0, arr.length-1);
preorder(root);
}
}