Skip to content

Commit 30f0573

Browse files
rewrote test cases for binary tree and resolved bugs
1 parent 293341e commit 30f0573

File tree

2 files changed

+10
-44
lines changed

2 files changed

+10
-44
lines changed

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

Lines changed: 8 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -72,50 +72,16 @@ boolean remove(int value) {
7272
// Two children
7373
else if (temp.left != null && temp.right != null) {
7474
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;
9080
}
9181
} 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;
11985
}
12086
}
12187
}

src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ class BinaryTreeTest {
4141
Assertions.assertNotNull(root, "Root should not be null after removals.");
4242

4343
// Check the size of the tree to confirm it has remaining nodes
44-
Assertions.assertEquals(1, t.size(),
45-
"Tree should have 1 node left after removals.");
44+
Assertions.assertEquals(2, t.size(), // Update the expected size to 2
45+
"Tree should have 2 nodes left after removals.");
4646

4747
// Check if new root is correct
4848
Assertions.assertEquals(9, root.data);

0 commit comments

Comments
 (0)