forked from srbcheema1/Algo_Ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchTree.java
123 lines (82 loc) · 2.12 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
123
/*
* @author Nikunj Khokhar
*/
public class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
BinarySearchTree() {
this.root = null;
}
void insert(int key) {
root = insertRec(root, key);
}
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
void preorder() {
preorderRec(root);
}
void preorderRec(Node root) {
if (root != null) {
System.out.println(root.key);
preorderRec(root.left);
preorderRec(root.right);
}
}
void postorder() {
postorderRec(root);
}
void postorderRec(Node root) {
if (root != null) {
postorderRec(root.left);
postorderRec(root.right);
System.out.println(root.key);
}
}
}
public class Main {
public static void main(String args[])
{
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert( 30);
tree.insert( 20);
tree.insert( 40);
tree.insert( 70);
tree.insert( 60);
tree.insert(80);
System.out.println("Inorder traversal of the given tree : ");
tree.inorder();
System.out.print("\n\n");
System.out.println("Postorder traversal of the given tree : ");
tree.postorder();
System.out.print("\n\n");
System.out.println("Preorder traversal of the given tree : ");
tree.preorder();
}
}