Skip to content

Commit 500b6bf

Browse files
author
Sarah Busert
committed
Fixed bug concerning deletion of item with two successors
1 parent e4b203e commit 500b6bf

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

BinarySearchTree/BinarySearchTree/BinarySearchTree.cs

+15-5
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,11 @@ public void DeleteNode(ref Node<T> root, T value)
7171

7272
private Node<T> Delete(ref Node<T> root)
7373
{
74+
var tempValue = default(T);
75+
7476
if (_globalRoot == root)
7577
{
76-
Console.WriteLine("Deletion of root element is not allowed");
78+
//Deletion of root element is not allowed;
7779
return root;
7880
}
7981
if (root.LeftNode == null && root.RightNode == null)
@@ -86,20 +88,28 @@ private Node<T> Delete(ref Node<T> root)
8688
}
8789
else if (root.RightNode == null)
8890
{
89-
root = root.LeftNode;
91+
root = root.LeftNode;
9092
}
9193
else
9294
{
93-
Replace(ref root);
95+
Replace(ref root, ref tempValue);
96+
root.Value = tempValue;
9497
}
9598
return root;
9699
}
97100

98-
private void Replace(ref Node<T> root)
101+
private static void Replace(ref Node<T> root, ref T newValue)
99102
{
103+
if (root == null) return;
100104
if (root.LeftNode == null)
105+
{
106+
newValue = root.Value;
101107
root = root.RightNode;
102-
else { Replace(ref root.LeftNode);}
108+
}
109+
else
110+
{
111+
Replace(ref root.LeftNode, ref newValue);
112+
}
103113
}
104114
}
105115
}

0 commit comments

Comments
 (0)