private TreeDictionary <TKey, TValue, TComparer> UpdateHelper( TKey key, Func <TValue, Optional <TValue> > updateFunc, out Optional <TValue> value, out bool needRebalance) { if (Count == 0) { value = Optional <TValue> .None; needRebalance = false; return(this); } int comparison = _Comparer.Compare(key, _key); if (comparison == 0) { value = _value; var newValue = updateFunc(_value); needRebalance = !newValue.HasValue; return(needRebalance ? GlueBalanced(_left, _right) : ReplaceValue(newValue.Value)); } if (comparison < 0) { var newLeft = _left.UpdateHelper(key, updateFunc, out value, out needRebalance); return(needRebalance ? NearlyBalanced(newLeft, _right) : Balanced(newLeft, _right)); } else { var newRight = _right.UpdateHelper(key, updateFunc, out value, out needRebalance); return(needRebalance ? NearlyBalanced(_left, newRight) : Balanced(_left, newRight)); } }