-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
75 lines (58 loc) · 1.73 KB
/
BinarySearchTree.java
File metadata and controls
75 lines (58 loc) · 1.73 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
/**
* This class serves as a container class. It has methods for inserting nodes and serching the tree.
*
* @Xuan Duong
*
*/
public class BinarySearchTree {
private Node root, temp;
//Constructor
public BinarySearchTree (){
root = null;
}
public void insert (String w) {
temp = new Node (w);//create new Node for the string
//check to see if the tree is empty
if (root == null) {
root = temp;
root.setFrequency(temp.getNum());
//Output first added word
System.out.println("Frequency: 1");
}else root.add(temp);//start recursive insert, setting the root as the initial subroot
}
public void search (String w) {
temp = new Node (w);
if (root == null) System.out.println("Word is not found!");
else root.find(temp);
}
public void printPreOrder (){
System.out.println("\nPrint Pre-Order");
preOrder(root);
}
public void printInOrder () {
System.out.println("\nPrint In-Order");
inOrder(root);
}
public void printPostOrder () {
System.out.println("\nPrint Post-Order");
postOrder(root);
}
public void preOrder (Node n) {
if (n == null) return;
n.result(n); //print root
preOrder(n.getLeft()); //left child
preOrder(n.getRight()); //right child
}
public void inOrder (Node n) {
if (n == null) return;
preOrder(n.getLeft()); //left child
n.result(n); //root
preOrder(n.getRight()); //right child
}
public void postOrder(Node n) {
if (n == null) return;
preOrder(n.getLeft()); //left child
preOrder(n.getRight()); //right child
n.result(n); //root
}
}