-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructBinarySearchTree.java
More file actions
47 lines (40 loc) · 1.35 KB
/
ConstructBinarySearchTree.java
File metadata and controls
47 lines (40 loc) · 1.35 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
package com.anudev.ds.trees;
/**
* Worst search time complexity in a binary search tree is O(h) where h
* is the height of the binary tree. height of binary search tree h = Log(n)
* i.e. number of elements in binary tree.
*
* Skewed right binary tree: tree which does not have any left subtree of
* its children too
*/
public class ConstructBinarySearchTree {
private static Node rootNode;
public static void constructBST(int[] array) {
rootNode = new Node(array[0]);
for (int i = 1; i < array.length; i++) {
Node node = rootNode;
while (true) {
int value = node.getValue();
if (value < array[i]) {
if (node.getRightNode() != null) {
node = node.getRightNode();
} else {
node.setRightNode(new Node(array[i]));
break;
}
} else {
if (node.getLeftNode() != null) {
node = node.getLeftNode();
} else {
node.setLeftNode(new Node(array[i]));
break;
}
}
}
}
System.out.println("BST created");
}
public static Node getRootNode() {
return rootNode;
}
}