@@ -72,31 +72,50 @@ 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
- successor .left = temp .left ;
76
- if (temp .left != null ) {
77
- temp .left .parent = successor ;
78
- }
79
- if (successor .parent != temp ) {
80
- if (successor .right != null ) {
81
- successor .right .parent = successor .parent ;
82
- successor .parent .left = successor .right ;
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
+ }
83
81
} else {
84
- successor .parent .left = null ;
85
- }
86
- successor .right = temp .right ;
87
- if (temp .right != null ) {
88
- temp .right .parent = successor ;
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
+ }
89
90
}
90
- }
91
- if (temp == root ) {
92
- successor .parent = null ;
93
- root = successor ;
94
91
} else {
95
- successor .parent = temp .parent ;
96
- if (temp .parent .data < temp .data ) {
97
- temp .parent .right = successor ;
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 ;
98
112
} else {
99
- temp .parent .left = successor ;
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
+ }
100
119
}
101
120
}
102
121
}
@@ -118,7 +137,6 @@ else if (temp.left != null && temp.right != null) {
118
137
}
119
138
}
120
139
121
- // Decrement size after successful removal
122
140
size --;
123
141
return true ;
124
142
}
0 commit comments