-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedArrayIntoBinarySearchTree.java
More file actions
58 lines (40 loc) · 1.29 KB
/
Copy pathConvertSortedArrayIntoBinarySearchTree.java
File metadata and controls
58 lines (40 loc) · 1.29 KB
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
54
55
56
57
58
public class ConvertSortedArrayIntoBinarySearchTree {
Node root;
public ConvertSortedArrayIntoBinarySearchTree(Node root) {
this.root = root;
}
public ConvertSortedArrayIntoBinarySearchTree() {
root = null;
}
static class Node {
int data;
Node left, right;
public Node(int data) {
this.data = data;
left = right = null;
}
}
public static void printInOrder(Node root) {
if (root == null) {
return;
}
printInOrder(root.left);
System.out.print(root.data + " ");
printInOrder(root.right);
}
public static Node convertToBinarySearchTree(int[] array, int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
Node root = new Node(array[mid]);
root.left = convertToBinarySearchTree(array, start, mid - 1);
root.right = convertToBinarySearchTree(array, mid + 1, end);
return root;
}
public static void main(String[] args) {
int[] array = {0, 2, 7, 9, 11, 13, 14};
Node root = convertToBinarySearchTree(array, 0, array.length - 1);
printInOrder(root);
}
}