From 8ac85d8a1f214a3abd02374d5a886c58f6d97351 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Thu, 14 Apr 2022 21:55:59 +0100 Subject: [PATCH] Added 'Delete' method to Binary Tree --- C#/Datastructures/BinaryTree/Tree.cs | 61 ++++++++++++++++++++++++++++ C#/Program.cs | 4 +- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/C#/Datastructures/BinaryTree/Tree.cs b/C#/Datastructures/BinaryTree/Tree.cs index 0445254..13803a8 100644 --- a/C#/Datastructures/BinaryTree/Tree.cs +++ b/C#/Datastructures/BinaryTree/Tree.cs @@ -48,6 +48,67 @@ namespace C_.Datastructures.BinaryTree 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>? 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? 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 + 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; + } + //Item being deleted is the right value + parent.Right = default; + } + Count--; + return true; + } + + private Stack>? Find(T value) {//Return true if the item can be found within the tree if (Root == default || Root.Value!.Equals(default)) diff --git a/C#/Program.cs b/C#/Program.cs index 96bcf3b..82a9763 100644 --- a/C#/Program.cs +++ b/C#/Program.cs @@ -119,10 +119,10 @@ tree.Add(6); tree.Add(2); tree.Add(3); tree.Add(1); -tree.Add(4); +tree.Add(8); tree.Add(7); -var x = tree.Find(2); +var x = tree.Delete(4); Console.ReadLine();