forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
122 lines (104 loc) · 2.64 KB
/
BinarySearchTree.java
File metadata and controls
122 lines (104 loc) · 2.64 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.examplehub.datastructures.binarytree;
import java.util.StringJoiner;
public class BinarySearchTree<E extends Comparable<E>> {
/** The root node binary search tree. */
private Node<E> root;
private final StringJoiner inOrderPath;
private final StringJoiner preOrderPath;
private final StringJoiner postOrderPath;
public BinarySearchTree() {
inOrderPath = new StringJoiner("->");
preOrderPath = new StringJoiner("->");
postOrderPath = new StringJoiner("->");
root = null;
}
public void insert(E key) {
root = insert(root, key);
}
public Node<E> insert(Node<E> root, E key) {
if (root == null) {
root = new Node<>(key);
} else if (key.compareTo(root.value) > 0) {
root.right = insert(root.right, key);
} else if (key.compareTo(root.value) < 0) {
root.left = insert(root.left, key);
}
return root;
}
public void delete(E key) {
if (search(key)) {
delete(root, key);
}
}
public Node<E> delete(Node<E> root, E key) {
if (root == null) {
return null;
}
if (key.compareTo(root.value) < 0) {
root.left = delete(root.left, key);
} else if (key.compareTo(root.value) > 0) {
root.right = delete(root.right, key);
} else {
// TODO
}
return null;
}
public boolean search(E key) {
return search(root, key);
}
public boolean search(Node<E> root, E key) {
if (root == null) {
return false;
}
if (key.compareTo(root.value) == 0) {
return true;
} else if (key.compareTo(root.value) < 0) {
return search(root.left, key);
} else {
return search(root.right, key);
}
}
public void inorder(Node<E> root) {
if (root != null) {
inorder(root.left);
inOrderPath.add(root.value.toString());
inorder(root.right);
}
}
public String getInorder() {
if (inOrderPath.length() == 0) {
inorder(root);
}
return inOrderPath.toString();
}
public void preOrder(Node<E> root) {
if (root != null) {
preOrderPath.add(root.value.toString());
preOrder(root.left);
preOrder(root.right);
}
}
public String getPreOrder() {
if (preOrderPath.length() == 0) {
preOrder(root);
}
return preOrderPath.toString();
}
public void postOrder(Node<E> root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
postOrderPath.add(root.value.toString());
}
}
public String getPostOrder() {
if (postOrderPath.length() == 0) {
postOrder(root);
}
return postOrderPath.toString();
}
@Override
public String toString() {
return getInorder();
}
}