private static int TreeLeaning(IImmutableTree <TKey, TValue> tree) { if (tree.IsEmpty) { return(0); } return(TreeHeight(tree.Right) - TreeHeight(tree.Left)); }
private IImmutableTree <TKey, TValue> RotateRightRight(IImmutableTree <TKey, TValue> tree) { if (tree.Left.IsEmpty) { return(tree); } var rotatedLeftChild = new ImmutableTree <TKey, TValue>(_comparer, _keyCloner, _valueCloner, tree.RootKey, tree.RootValue, RotateLeft(tree.Left), tree.Right); return(RotateRight(rotatedLeftChild)); }
private IImmutableTree <TKey, TValue> RotateRight(IImmutableTree <TKey, TValue> tree) { if (tree.Left.IsEmpty) { return(tree); } return(new ImmutableTree <TKey, TValue>(_comparer, _keyCloner, _valueCloner, tree.Left.RootKey, tree.Left.RootValue, tree.Left.Left, new ImmutableTree <TKey, TValue>(_comparer, _keyCloner, _valueCloner, tree.RootKey, tree.RootValue, tree.Left.Right, tree.Right))); }
internal ImmutableTree(IComparer <TKey> comparer, Func <TKey, TKey> keyCloner, Func <TValue, TValue> valueCloner, TKey key, TValue value, IImmutableTree <TKey, TValue> left, IImmutableTree <TKey, TValue> right) { _comparer = comparer; _keyCloner = keyCloner; _valueCloner = valueCloner; _key = key; _value = value; _left = left; _right = right; _height = 1 + Math.Max(TreeHeight(_left), TreeHeight(_right)); Count = 1 + Left.Count + Right.Count; }
private IEnumerable <IImmutableTree <TKey, TValue> > Descending() { var st = ImmutableStack <IImmutableTree <TKey, TValue> > .Start; for (IImmutableTree <TKey, TValue> each = this; !each.IsEmpty || !st.IsEmpty; each = each.Left) { while (!each.IsEmpty) { st = st.Push(each); each = each.Right; } each = st.Peek(); st = st.Pop(); yield return(each); } }
private IImmutableTree <TKey, TValue> BalanceTree(IImmutableTree <TKey, TValue> tree) { IImmutableTree <TKey, TValue> result; if (RightHeavy(tree)) { result = LeansLeft(tree.Right) ? RotateLeftLeft(tree) : RotateLeft(tree); } else if (LeansLeft(tree)) { result = RightHeavy(tree.Left) ? RotateRightRight(tree) : RotateRight(tree); } else { result = tree; } return(result); }
private static bool LeansLeft(IImmutableTree <TKey, TValue> tree) { return(TreeLeaning(tree) <= _negHeavy); }
private static bool RightHeavy(IImmutableTree <TKey, TValue> tree) { return(TreeLeaning(tree) >= _heavy); }
private static int TreeHeight(IImmutableTree <TKey, TValue> tree) { return(tree.IsEmpty ? 0 : ((ImmutableTree <TKey, TValue>)tree)._height); }