@@ -45,7 +45,7 @@ public boolean isEmpty() {
45
45
*
46
46
* @param key The key to insert.
47
47
*/
48
- public final void insert (int key ) {
48
+ public void insert (final int key ) {
49
49
root = insertRec (root , key );
50
50
root = splay (root , key );
51
51
}
@@ -67,29 +67,42 @@ public boolean search(int key) {
67
67
* @param key The key to delete.
68
68
* @throws IllegalArgumentException If the tree is empty.
69
69
*/
70
- public final void delete (int key ) {
70
+ public void delete (final int key ) {
71
71
if (isEmpty ()) {
72
72
throw new EmptyTreeException ("Cannot delete from an empty tree" );
73
73
}
74
74
75
- // Splay the tree with the key to be deleted
76
75
root = splay (root , key );
77
76
78
- // If the key is not found at the root, return without deleting
79
77
if (root .key != key ) {
80
78
return ;
81
79
}
82
80
83
- // Handle deletion
84
81
if (root .left == null ) {
85
82
root = root .right ;
86
83
} else {
87
- // Splay to bring the largest key in left subtree to root
88
84
Node temp = root ;
89
- root = splay (root .left , key );
85
+ root = splay (root .left , findMax ( root . left ). key );
90
86
root .right = temp .right ;
91
87
}
92
88
}
89
+ /**
90
+ * Finds the node with the maximum key in a given subtree.
91
+ *
92
+ * <p>
93
+ * This method traverses the right children of the subtree until it finds the
94
+ * rightmost node, which contains the maximum key.
95
+ * </p>
96
+ *
97
+ * @param root The root node of the subtree.
98
+ * @return The node with the maximum key in the subtree.
99
+ */
100
+ private Node findMax (Node root ) {
101
+ while (root .right != null ) {
102
+ root = root .right ;
103
+ }
104
+ return root ;
105
+ }
93
106
94
107
/**
95
108
* Perform a traversal of the SplayTree.
@@ -177,7 +190,7 @@ private Node rotateLeft(Node x) {
177
190
* @param key The key to splay around.
178
191
* @return The new root of the splayed subtree.
179
192
*/
180
- private Node splay (Node root , int key ) {
193
+ private Node splay (Node root , final int key ) {
181
194
if (root == null || root .key == key ) {
182
195
return root ;
183
196
}
@@ -215,7 +228,7 @@ private Node splay(Node root, int key) {
215
228
}
216
229
}
217
230
218
- private Node insertRec (Node root , int key ) {
231
+ private Node insertRec (Node root , final int key ) {
219
232
if (root == null ) {
220
233
return new Node (key );
221
234
}
@@ -232,12 +245,16 @@ private Node insertRec(Node root, int key) {
232
245
}
233
246
234
247
public static class EmptyTreeException extends RuntimeException {
248
+ private static final long serialVersionUID = 1L ;
249
+
235
250
public EmptyTreeException (String message ) {
236
251
super (message );
237
252
}
238
253
}
239
254
240
255
public static class DuplicateKeyException extends RuntimeException {
256
+ private static final long serialVersionUID = 1L ;
257
+
241
258
public DuplicateKeyException (String message ) {
242
259
super (message );
243
260
}
0 commit comments