/// <summary> /// Deletes the given value from the tree at the given root according to the BinarySearchTree algorithm and then /// rebalances the tree. /// </summary> /// <param name="root">The root node of the tree</param> /// <param name="value">The value to delete</param> /// <returns>The new root of the tree as it may have changed</returns> private AVLNode <T> Delete(AVLNode <T> root, T value) { int compareResults = root.Value.CompareTo(value); if (compareResults > 0) { if (root.Left != null) { root.ResetHeight(); root.Left = Delete(root.Left, value); } else { throw new ValueNotFoundException(); } } else if (compareResults < 0) { if (root.Right != null) { root.ResetHeight(); root.Right = Delete(root.Right, value); } else { throw new ValueNotFoundException(); } } else { if (root.Left == null && root.Right == null) { --this.Count; root = null; } else if (root.Right == null) { --this.Count; root.Value = root.Left.Value; root.Right = root.Left.Right; root.Left = root.Left.Left; root.ResetHeight(); } else if (root.Left == null) { --this.Count; root.Value = root.Right.Value; root.Left = root.Right.Left; root.Right = root.Right.Right; root.ResetHeight(); } else { AVLNode <T> predecessor = root.InOrderPredecessor; root.Value = predecessor.Value; root.Left = Delete(root.Left, predecessor.Value); root.ResetHeight(); } } if (root != null) { root = RebalanceNode(root); } return(root); }
private int GetChildNodeHeight(AVLNode <T> node) { return((node == null) ? -1 : node.Height); }