-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinarySearchTree.java
48 lines (42 loc) · 1.15 KB
/
BinarySearchTree.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
42
43
44
45
46
47
48
public class BinarySearchTree {
private Node root;
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(1);
bst.insert(4);
bst.insert(6);
System.out.println(bst.root.value);
}
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.value > value) {
current = current.left;
} else {
current = current.right;
}
}
current = new Node(value);
if (parent.value > value) {
parent.left = current;
} else {
parent.right = current;
}
}
}
private static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
}