Repository navigation
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
93 lines (80 loc) · 2.21 KB
/
Copy pathBinarySearchTree.java
File metadata and controls
93 lines (80 loc) · 2.21 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
/**
* BinarySearchTree class: Implements a Binary Search Tree (BST)
* with insertion, deletion, and traversal operations.
*/
public class BinarySearchTree {
// Node class for BST
public static 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() {
this.root = null;
}
// Insert operation
public void insert(int data) {
root = insertRec(root, data);
}
private Node insertRec(Node root, int data) {
if (root == null) {
return new Node(data);
}
if (data < root.data) {
root.left = insertRec(root.left, data);
} else if (data > root.data) {
root.right = insertRec(root.right, data);
}
return root;
}
// Delete operation
public void delete(int data) {
root = deleteRec(root, data);
}
private Node deleteRec(Node root, int data) {
if (root == null) {
return root;
}
if (data < root.data) {
root.left = deleteRec(root.left, data);
} else if (data > root.data) {
root.right = deleteRec(root.right, data);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}
root.data = minValue(root.right);
root.right = deleteRec(root.right, root.data);
}
return root;
}
private int minValue(Node root) {
int minValue = root.data;
while (root.left != null) {
minValue = root.left.data;
root = root.left;
}
return minValue;
}
// Inorder traversal
public void inorderTraversal() {
System.out.print("Inorder Traversal: ");
inorderRec(root);
System.out.println();
}
private void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}
}
}