Re-Written Delete method on Binary Tree
This commit is contained in:
parent
6ae360f3bc
commit
564e4d161f
@ -78,31 +78,38 @@ namespace C_.Datastructures.BinaryTree
|
||||
//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
|
||||
|
||||
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<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;
|
||||
}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--;
|
||||
|
@ -112,15 +112,17 @@ Console.WriteLine("Hello, World!");
|
||||
|
||||
Tree<int> tree = new Tree<int>();
|
||||
|
||||
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);
|
||||
|
Loading…
Reference in New Issue
Block a user