diff --git a/C#/Datastructures/BinaryTree/Tree.cs b/C#/Datastructures/BinaryTree/Tree.cs index 84a9cf4..27baf43 100644 --- a/C#/Datastructures/BinaryTree/Tree.cs +++ b/C#/Datastructures/BinaryTree/Tree.cs @@ -78,31 +78,38 @@ namespace C_.Datastructures.BinaryTree //Delete Item (replace) and replace pointers to retain integrity of tree TreeNode? node = deletionStack.Pop(); - TreeNode? parent = deletionStack.Pop(); //stack to store the items leading up to the value that we will use to replace the node Stack>? replacementStack = Min(node!.Right); - if (replacementStack != default) - {//If there are values to the right + + if (replacementStack == default) + {//Nothing to the right of the value we are deleting + if (deletionStack.Peek() != default) + {//Parent adopts left hand side of node if present + deletionStack.Pop()!.Left = node.Left; + } + + if (node.Left != default) + {//Node adopts left value if no lower value to the right + node.Value = node.Left!.Value; + node.Left = node.Left.Left; + } + } + else + {//Replace the value + reorder nodes + node.Value = replacementStack.Peek()!.Value; TreeNode? replacementNode = replacementStack.Pop(); - node.Value = replacementNode!.Value; - - //Remove the node that we have taken the value from - if (replacementStack.Peek() != default) - {//If the parent is not the node that we replaced - replacementStack.Pop()!.Left = replacementNode.Right; - }else{//If the parent is the node what we replaced - node.Right = replacementNode.Right; - } - }else{ - //Parent's relation needs to be set to null as there are no greater values - if (node.Value!.CompareTo(parent!.Value) < 0) - {//Item being deleted is the left child - parent.Left = default; - }else{ - //Item being deleted is the right value - parent.Right = default; + switch (replacementStack.GetCount()) + {//Determine what to do based on number of items in replacement stack + case 1: + node.Right = replacementNode!.Right; + break; + case >=2: + replacementStack.Peek()!.Left = replacementNode!.Right; + break; + default: + break; } } Count--; diff --git a/C#/Program.cs b/C#/Program.cs index 6de20e1..0582bce 100644 --- a/C#/Program.cs +++ b/C#/Program.cs @@ -112,15 +112,17 @@ Console.WriteLine("Hello, World!"); Tree tree = new Tree(); -tree.Add(5); -tree.Add(4); +tree.Add(10); +tree.Add(8); +tree.Add(6); tree.Add(3); +tree.Add(4); +tree.Add(5); tree.Add(2); -tree.Add(1); tree.Add(0); -var x = tree.Delete(3); +var x = tree.Delete(10); //tree.Delete(5); var l = tree.Inorder(null);