Fixed delete method - Or maybe not

This commit is contained in:
lukejelse04 2021-07-07 12:30:08 +01:00
parent 615b157123
commit 32fbf6f4ec
2 changed files with 27 additions and 17 deletions

View File

@ -7,16 +7,18 @@ namespace BinaryTree
static void Main(string[] args) static void Main(string[] args)
{ {
tree tree = new tree(); tree tree = new tree();
tree.Add(5);
tree.Add(7);
tree.Add(6);
tree.Add(8);
tree.Add(3);
tree.Add(1);
tree.Add(4);
tree.Add(0.5);
tree.Delete(1); Random random = new Random();
for (var i = 0; i < 1000; i++)
{
tree.Add(random.Next(0, 10000));
}
tree.Delete(tree.Root.Data);
Console.ReadLine(); Console.ReadLine();

View File

@ -82,8 +82,9 @@ namespace BinaryTree
if (Current.GetLeft() != null && Current.GetRight() != null) if (Current.GetLeft() != null && Current.GetRight() != null)
{ {
//If it has 2 children //If it has 2 children
node temp = new node(); node temp = Current.GetLeft();
temp = Current.GetLeft();
//Traverse to node that will replace Current
while(true){ while(true){
if (temp.GetRight() != null) if (temp.GetRight() != null)
{ {
@ -94,14 +95,22 @@ namespace BinaryTree
} }
Current.Data = temp.Data; Current.Data = temp.Data;
//Find if the temp node is a left or a right now before deleting.
//Adopt subtree Nodes// -- Subtrees are lost (If temp node is only 1 level down, data is lost)
// if (temp.GetLeft() != null)
// {
// temp.GetParent().SetRight(temp.GetLeft());
// }else{
// temp.GetParent().SetRight(null);
// }
if (temp.GetLeft() != null)
{ if(temp.GetParent() == Current){
temp.GetParent().SetRight(temp.GetLeft()); Current.SetLeft(null);
}else{ }else{
temp.GetParent().SetRight(null); Current.SetLeft(temp.GetLeft());
} }
return true; return true;
@ -136,6 +145,5 @@ namespace BinaryTree
} }
} }
} }