@@ -72,50 +72,16 @@ boolean remove(int value) {
72
72
// Two children
73
73
else if (temp .left != null && temp .right != null ) {
74
74
Node successor = findSuccessor (temp );
75
- if (successor == temp ) { // Handle case where successor is the node itself
76
- if (temp == root ) {
77
- root = temp .left ;
78
- if (root != null ) {
79
- root .parent = null ;
80
- }
81
- } else {
82
- if (temp .parent .data < temp .data ) {
83
- temp .parent .right = temp .left ;
84
- } else {
85
- temp .parent .left = temp .left ;
86
- }
87
- if (temp .left != null ) {
88
- temp .left .parent = temp .parent ;
89
- }
75
+ temp .data = successor .data ; // Replace temp's data with successor's data
76
+ if (successor == successor .parent .left ) {
77
+ successor .parent .left = successor .right ;
78
+ if (successor .right != null ) {
79
+ successor .right .parent = successor .parent ;
90
80
}
91
81
} else {
92
- // Existing logic for successor not being the node itself
93
- successor .left = temp .left ;
94
- if (temp .left != null ) {
95
- temp .left .parent = successor ;
96
- }
97
- if (successor .parent != temp ) {
98
- if (successor .right != null ) {
99
- successor .right .parent = successor .parent ;
100
- successor .parent .left = successor .right ;
101
- } else {
102
- successor .parent .left = null ;
103
- }
104
- successor .right = temp .right ;
105
- if (temp .right != null ) {
106
- temp .right .parent = successor ;
107
- }
108
- }
109
- if (temp == root ) {
110
- successor .parent = null ;
111
- root = successor ;
112
- } else {
113
- successor .parent = temp .parent ;
114
- if (temp .parent .data < temp .data ) {
115
- temp .parent .right = successor ;
116
- } else {
117
- temp .parent .left = successor ;
118
- }
82
+ successor .parent .right = successor .right ;
83
+ if (successor .right != null ) {
84
+ successor .right .parent = successor .parent ;
119
85
}
120
86
}
121
87
}
0 commit comments