Added 'Delete' method to Binary Tree

This commit is contained in:
Luke Else 2022-04-14 21:55:59 +01:00
parent 1c14ff75d6
commit 8ac85d8a1f
2 changed files with 63 additions and 2 deletions

View File

@ -48,6 +48,67 @@ namespace C_.Datastructures.BinaryTree
return; return;
} }
public bool Delete(T value)
{
//Check if root of tree is null
if (Count == 0)
return false;
//Check if value is the root
if (Count == 1)
{
if (Root!.Value!.Equals(value))
{//If the only item is the one we are trying to delete
Count = 0;
Root = default;
return true;
}
return false;
}
//Stack to store the items leading up to and including the one we are trying to delete
Stack<TreeNode<T>>? deletionStack;
//Search for item being deleted + Parents
deletionStack = Find(value);
if (deletionStack == default)
return false; //Item was not found
//Delete Item (replace) and replace pointers to retain integrity of tree
TreeNode<T>? node = deletionStack.Pop();
TreeNode<T>? parent = deletionStack.Pop();
//stack to store the items leading up to the value that we will use to replace the node
Stack<TreeNode<T>>? replacementStack = Min(node!.Right);
if (replacementStack != default)
{//If there are values to the right
TreeNode<T>? 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;
}
//Item being deleted is the right value
parent.Right = default;
}
Count--;
return true;
}
private Stack<TreeNode<T>>? Find(T value) private Stack<TreeNode<T>>? Find(T value)
{//Return true if the item can be found within the tree {//Return true if the item can be found within the tree
if (Root == default || Root.Value!.Equals(default)) if (Root == default || Root.Value!.Equals(default))

View File

@ -119,10 +119,10 @@ tree.Add(6);
tree.Add(2); tree.Add(2);
tree.Add(3); tree.Add(3);
tree.Add(1); tree.Add(1);
tree.Add(4); tree.Add(8);
tree.Add(7); tree.Add(7);
var x = tree.Find(2); var x = tree.Delete(4);
Console.ReadLine(); Console.ReadLine();