-
Notifications
You must be signed in to change notification settings - Fork 1
/
BST.java
41 lines (37 loc) · 976 Bytes
/
BST.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
/**
* BST
*/
public class BST {
Node root;
public static void main(String[] args) {
BST bst = new BST();
bst.insert(5);
bst.insert(3);
bst.insert(1);
bst.insert(4);
bst.insert(6);
System.out.println(bst.root.getValue());
}
public void insert(int value) {
if (root == null) {
root = new Node(value);
} else {
Node current = root;
Node parent = root;
while (current != null) {
parent = current;
if (current.getValue() > value) {
current = current.getLeft();
} else {
current = current.getRight();
}
}
current = new Node(value);
if (parent.getValue() > value) {
parent.setLeft(current);
} else {
parent.setRight(current);
}
}
}
}