private BinaryTreeNode <T> FindNodeAndParent(T value, BinaryTreeNode <T> current, ref BinaryTreeNode <T> parent) { var comparison = value.CompareTo(current.Value); while (comparison != 0) { if (comparison > 0) // value is bigger than current node search right subtree { parent = current; current = current.RightChild; } else if (comparison < 0) // value is smaller than current node search left subtree { parent = current; current = current.LeftChild; } if (current is null) { return(current); } else { comparison = value.CompareTo(current.Value); } } return(current); }
public BinarySearchTree(BinaryTreeNode <T> root) : base(root) { }
public void DeleteByValue(T value) { BinaryTreeNode <T> parent = null; var toRemove = FindNodeAndParent(value, Root, ref parent); var position = toRemove.CompareTo(parent); // Case 1: if toRemove has no right child replace with leftChild if (toRemove.RightChild is null) { if (position < 0) { parent.LeftChild = toRemove.LeftChild; // replace parent left child with left child of the node you want to remove; } else if (position > 0) { parent.RightChild = toRemove.LeftChild; // replace parent right child with left child of the node you want to remove; } else { throw new Exception("Current node is the same as its parent... You've got a bug! (or a single node tree)"); } } // Case 2: if toRemove right child has no left child replace with rightChild else if (toRemove.RightChild.LeftChild is null) { if (position < 0) { parent.LeftChild = toRemove.RightChild; // replace parent right child with left child of the node you want to remove; parent.LeftChild.LeftChild = toRemove.LeftChild ?? null; } else if (position > 0) { parent.RightChild = toRemove.RightChild; // replace parent right child with right child of the node you want to remove; parent.RightChild.LeftChild = toRemove.LeftChild ?? null; } else { throw new Exception("Current node is the same as its parent... You've got a bug! (or a single node tree)"); } } // Case 3: if toRemove right child has left child replace with toRemove.rightChild's leftmost descendant else if (toRemove.RightChild.LeftChild != null) { if (position < 0) { parent.LeftChild = FindLeftmostDescendant(toRemove.RightChild); parent.LeftChild.LeftChild = toRemove.LeftChild ?? null; parent.LeftChild.RightChild = toRemove.RightChild ?? null; } else if (position > 0) { var replacement = FindLeftmostDescendant(toRemove.RightChild); FindParentNode(replacement).RemoveLeftChild(); parent.RightChild = replacement; parent.RightChild.LeftChild = toRemove.LeftChild ?? null; parent.RightChild.RightChild = toRemove.RightChild ?? null; } else { throw new Exception("Current node is the same as its parent... You've got a bug! (or a single node tree)"); } } _nodes.Remove(toRemove); }