-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23_BST.java
More file actions
120 lines (111 loc) · 3.52 KB
/
23_BST.java
File metadata and controls
120 lines (111 loc) · 3.52 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
import java.util.Scanner;
class BSTNode {
int data;
BSTNode left, right;
BSTNode(int value) {
data = value;
left = right = null;
}
}
public class BST {
BSTNode root;
BSTNode insert(BSTNode root, int key) {
if (root == null) {
return new BSTNode(key);
}
if (key < root.data)
root.left = insert(root.left, key);
else if (key > root.data)
root.right = insert(root.right, key);
return root;
}
boolean search(BSTNode root, int key) {
if (root == null)
return false;
if (key == root.data)
return true;
if (key < root.data)
return search(root.left, key);
else
return search(root.right, key);
}
int minValue(BSTNode root) {
int min = root.data;
while (root.left != null) {
min = root.left.data;
root = root.left;
}
return min;
}
BSTNode delete(BSTNode root, int key) {
if (root == null)
return root;
if (key < root.data)
root.left = delete(root.left, key);
else if (key > root.data)
root.right = delete(root.right, key);
else {
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
int minValue = minValue(root.right);
root.data = minValue;
root.right = delete(root.right, minValue);
}
return root;
}
void inorder(BSTNode root) {
if (root != null) {
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BST tree = new BST();
int choice, value;
do {
System.out.println("\n--- BST MENU ---");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Search");
System.out.println("4. Display (Inorder)");
System.out.println("5. Exit");
System.out.print("Enter choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter value to insert: ");
value = sc.nextInt();
tree.root = tree.insert(tree.root, value);
break;
case 2:
System.out.print("Enter value to delete: ");
value = sc.nextInt();
tree.root = tree.delete(tree.root, value);
break;
case 3:
System.out.print("Enter value to search: ");
value = sc.nextInt();
if (tree.search(tree.root, value))
System.out.println("Element found.");
else
System.out.println("Element not found.");
break;
case 4:
System.out.print("BST Inorder: ");
tree.inorder(tree.root);
System.out.println();
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
}
} while (choice != 5);
sc.close();
}
}