- Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathSortedArrayToBalancedTree.java
More file actions
Latest commit
54 lines (44 loc) · 1.45 KB
/
Copy pathSortedArrayToBalancedTree.java
File metadata and controls
54 lines (44 loc) · 1.45 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
packagetrees.sortedarraytobalancedtree;
importtrees.model.BinarySearchTree;
importtrees.model.BinarySearchTreeImpl;
importtrees.model.TraverseType;
importjava.util.List;
/**
* Given a sorted array, create a balanced tree.
* Created by techpanja
* Created on 1/20/14 12:56 PM.
*/
publicclassSortedArrayToBalancedTree {
privatestaticBinarySearchTree<Integer> searchTree;
privateSortedArrayToBalancedTree() {
}
publicstaticBinarySearchTreecreateBalancedTree(int[] inputArray) {
searchTree = newBinarySearchTreeImpl();
if (inputArray.length < 1) {
returnsearchTree;
}
intlow = 0;
inthigh = inputArray.length - 1;
createBalancedTree(inputArray, low, high);
returnsearchTree;
}
/*
* Follow binary search technique to insert nodes into the tree.
* */
privatestaticvoidcreateBalancedTree(int[] inputArray, intlow, inthigh) {
if (high < low) {
return;
}
intmid = (low + high) / 2;
searchTree.insertNode(inputArray[mid]);
createBalancedTree(inputArray, low, mid - 1);
createBalancedTree(inputArray, mid + 1, high);
}
publicstaticvoidmain(String[] args) {
createBalancedTree(newint[]{2, 5, 6, 8, 11, 22, 33});
List<Integer> list = searchTree.traverseTree(TraverseType.INORDER);
for (Integeri : list) {
System.out.println(i);
}
}
}