forked from Anubhav-1020/Hacktoberfest-Beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.java
122 lines (98 loc) · 2.99 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
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
public class BinarySearchTreeApp {
public static void main(String[] args) {
BSTree t = new BSTree();
t.addNode(10);
t.addNode(5);
t.addNode(3);
t.addNode(20);
t.addNode(6);
t.addNode(15);
t.addNode(2);
t.addNode(25);
System.out.println("----In Order------");
t.inOrderTraversal(t.root);
System.out.println("-----Pre Order-----");
t.preOrderTraversal(t.root);
System.out.println("----Post Order------");
t.postOrderTraversal(t.root);
System.out.println("finding 6 " + t.findNode(6));
System.out.println("finding 9 " + t.findNode(9));
}
}
class BSTNode {
int data;
BSTNode leftChild;
BSTNode rightChild;
public BSTNode(int data) {
this.data = data;
}
public String toString() {
return "data -> " + data;
}
}
class BSTree {
BSTNode root;
public void addNode(int data) {
BSTNode newNode = new BSTNode(data);
if (root == null) {
root = newNode;
} else {
BSTNode currentNode = root;
while (true) {
BSTNode parentNode = currentNode;
if (newNode.data < currentNode.data) {
currentNode = currentNode.leftChild;
if (currentNode == null) {
parentNode.leftChild = newNode;
return;
}
} else {
currentNode = currentNode.rightChild;
if (currentNode == null) {
parentNode.rightChild = newNode;
return;
}
}
}
}
}
public BSTNode findNode(int data) {
BSTNode currentNode = root;
while (currentNode != null) {
if (data == currentNode.data) {
return currentNode;
} else {
if (data < currentNode.data) {
currentNode = currentNode.leftChild;
} else {
currentNode = currentNode.rightChild;
}
}
}
return null;
}
public void preOrderTraversal(BSTNode currentNode) {
if (currentNode == null) {
return;
}
System.out.println(currentNode);
preOrderTraversal(currentNode.leftChild);
preOrderTraversal(currentNode.rightChild);
}
public void postOrderTraversal(BSTNode currentNode) {
if (currentNode == null) {
return;
}
postOrderTraversal(currentNode.leftChild);
postOrderTraversal(currentNode.rightChild);
System.out.println(currentNode);
}
public void inOrderTraversal(BSTNode currentNode) {
if (currentNode == null) {
return;
}
inOrderTraversal(currentNode.leftChild);
System.out.println(currentNode);
inOrderTraversal(currentNode.rightChild);
}
}