/// <summary> /// Recursive insertion with balancing on every step. /// </summary> private AVLTreeNode <T> Add(AVLTreeNode <T> node, T value) { if (node == null) { return(new AVLTreeNode <T>(value)); } int cmp = comparer.Compare(value, node.Value); if (cmp < 0) { node.Left = Add(node.Left, value); } else if (cmp > 0) { node.Right = Add(node.Right, value); } else { throw new ArgumentException("Tried to insert duplicate value!"); } return(Balance(node)); }
/// <summary> /// Calculates the balance factor. /// </summary> private int BalanceFactor(AVLTreeNode <T> node) { return(NodeHeight(node.Left) - NodeHeight(node.Right)); }
/// <summary> /// Gets the node height. Returns 0 if node is null. /// </summary> private int NodeHeight(AVLTreeNode <T> node) { return(node?.Height ?? 0); }