/// <summary> /// Default constructor /// </summary> public BinarySearchTree() { _root = null; Count = 0; _comparer = Comparer <T> .Default; }
/// <summary> /// Removes element from the binary search tree /// </summary> /// <param name="value">Value to remove</param> /// <returns>True, if tree doesn't contain same value, false otherwise</returns> public bool Remove(T value) { if (!Contains(value)) { return(false); } BinarySearchTreeNode <T> parent = null; BinarySearchTreeNode <T> current = FindWithParent(value, out parent); BinarySearchTreeNode <T> replacementNode = null; BinarySearchTreeNode <T> replacementNodeParent = null; if (current.Right == null) { replacementNode = current.Left; } else if (current.Left == null) { replacementNode = current.Right; } else { replacementNodeParent = current; replacementNode = current.Left; while (replacementNode.Right != null) { replacementNodeParent = replacementNode; replacementNode = replacementNode.Right; } if (replacementNodeParent == current) { replacementNode.Right = current.Right; } else { replacementNode.Right = current.Right; replacementNodeParent.Right = replacementNode.Left; replacementNode.Left = replacementNodeParent; } } if (current == _root) { _root = replacementNode; } else if (_comparer.Compare(current.Value, parent.Value) < 0) { parent.Left = replacementNode; } else { parent.Right = replacementNode; } Count--; return(true); }