-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
123 lines (119 loc) · 3.72 KB
/
BinarySearchTree.java
File metadata and controls
123 lines (119 loc) · 3.72 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
123
import java.util.Scanner;
public class BinarySearchTree {
public class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
public Node root;
public BinarySearchTree(){
root = null;
}
public void insert(int data){
Node newNode = new Node(data);
if(root==null){
root = newNode;
return;
}
else{
Node current = root, parent = null;
while (current!=null) {
parent = current;
if(data < current.data){
current = current.left;
if(current == null){
parent.left = newNode;
}
}
else{
current = current.right;
if(current==null){
parent.right = newNode;
}
}
}
}
}
public void inOrderTraversal(Node node){
if(root==null){
System.out.println("Tree Empty");
}
else{
if(node.left!=null){
inOrderTraversal(node.left);
}
System.out.print(node.data+" ");
if(node.right!=null){
inOrderTraversal(node.right);
}
}
}
public void preOrderTraversal(Node node){
if(root==null){
System.out.println("Tree Empty");
}
else{
System.out.print(node.data+" ");
if(node.left!=null){
inOrderTraversal(node.left);
}
if(node.right!=null){
inOrderTraversal(node.right);
}
}
}
public void postOrderTraversal(Node node){
if(root==null){
System.out.println("Tree Empty");
}
else{
if(node.left!=null){
inOrderTraversal(node.left);
}
if(node.right!=null){
inOrderTraversal(node.right);
}
System.out.print(node.data+" ");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BinarySearchTree bst = new BinarySearchTree();
int choice = 0;
do {
System.out.println("Binary Search Tree Menu\n1. Insert a node\n2. Inorder Traversal\n3. Preorder Traversal\n4. Postorder Traversal\n5. Exit\nEnter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the node value: ");
int value = sc.nextInt();
bst.insert(value);
break;
case 2:
System.out.println("Inorder Traversal:");
bst.inOrderTraversal(bst.root);
break;
case 3:
System.out.println("Preorder Traversal:");
bst.preOrderTraversal(bst.root);
break;
case 4:
System.out.println("Postorder Traversal:");
bst.postOrderTraversal(bst.root);
break;
case 5:
System.out.println("Exiting...");
sc.close();
break;
default:
System.out.println("Invalid choice. Please try again.");
break;
}
} while (choice != 5);
}
}