-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
96 lines (73 loc) · 1.84 KB
/
BinarySearchTree.java
File metadata and controls
96 lines (73 loc) · 1.84 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Implement binary Search Tree
* following operations
* insert element
* search
*/
class Node<T> {
T data;
Node<T> left;
Node<T> right;
Node<T> parent;
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
this.left = null;
this.right = null;
}
public T getData() {
return data;
}
public Node<T> getLeft() {
return left;
}
public Node<T> getRight() {
return right;
}
public void setLeft(Node<T> left) {
this.left = left;
}
public void setRight(Node<T> right) {
this.right = right;
}
}
public class BinarySearchTree<T extends Comparable<T>> {
private Node<T> root;
public BinarySearchTree() {
root = null;
}
//insert data into a new node
public void insert(T data) {
root = insert(data, root);
}
public Node<T> insert(T data, Node<T> curr) {
if (curr == null) {
return new Node(data, curr);
}
int comp = data.compareTo(curr.getData());
if (comp < 0) {
curr.setLeft(insert(data, curr.getLeft()));
} else if (comp > 0) {
curr.setRight(insert(data, curr.getRight()));
}
return curr;
}
public boolean preorder(Node<T> curr) {
if (curr == null) {
return false;
}
System.out.print(curr.getData() + " " );
preorder(curr.getLeft());
preorder(curr.getRight());
return true;
}
public static void main(String[] args) {
String[] arrFill = {"50", "15", "72", "49", "73"};
BinarySearchTree<String> bst = new BinarySearchTree<>();
for (String st : arrFill) {
bst.insert(st);
}
bst.preorder(bst.root);
System.out.println();
}
}