Skip to content

Commit a85fd14

Browse files
resolved error in binary tree
1 parent 4bdab42 commit a85fd14

File tree

1 file changed

+40
-22
lines changed

1 file changed

+40
-22
lines changed

src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java

Lines changed: 40 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -72,31 +72,50 @@ boolean remove(int value) {
7272
// Two children
7373
else if (temp.left != null && temp.right != null) {
7474
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+
}
8381
} 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+
}
8990
}
90-
}
91-
if (temp == root) {
92-
successor.parent = null;
93-
root = successor;
9491
} 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;
98112
} 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+
}
100119
}
101120
}
102121
}
@@ -118,7 +137,6 @@ else if (temp.left != null && temp.right != null) {
118137
}
119138
}
120139

121-
// Decrement size after successful removal
122140
size--;
123141
return true;
124142
}

0 commit comments

Comments
 (0)