public static ulong CountLeftThis <T>(this MedianTreeNode <T> tree) { if (tree == null) { return(0); } return(tree.Left.CountThis()); }
public static ulong CountRight <T>(this MedianTreeNode <T> tree) { if (tree == null) { return(0); } return(tree.CountRight); }
public static ulong Count <T>(this MedianTreeNode <T> tree) { if (tree == null) { return(0); } checked { return(tree.CountLeft + tree.CountThis + tree.CountRight); } }
public void Add(T value, ulong count) { root = root.Add(value, count, comparer); }
public static MedianTreeNode <T> Add <T>(this MedianTreeNode <T> tree, T value, ulong count, IComparer <T> comparer) { if (tree == null) { return new MedianTreeNode <T>() { Key = value, CountThis = count } } ; MedianTreeNode <T> current = tree; Stack <Tuple <MedianTreeNode <T>, bool> > parents = new Stack <Tuple <MedianTreeNode <T>, bool> >(); do { int cmp = comparer.Compare(value, current.Key); if (cmp < 0) { checked { current.CountLeft += count; } if (current.Left == null) { current.Left = new MedianTreeNode <T>() { Key = value, CountThis = count }; break; } else { parents.Push(Tuple.Create(current, true)); current = current.Left; } } else if (cmp > 0) { checked { current.CountRight += count; } if (current.Right == null) { current.Right = new MedianTreeNode <T>() { Key = value, CountThis = count }; break; } else { parents.Push(Tuple.Create(current, false)); current = current.Right; } } else //cmp==0 { checked { current.CountThis += count; } break; } } while(true); //now balance the tree while (parents.Count > 0) { var t = parents.Pop(); MedianTreeNode <T> parent = t.Item1; bool leftOf = t.Item2; if (leftOf) { if (SumIsPositive( new ulong[] { current.CountThis, current.CountLeft, current.CountLeft }, new ulong[] { parent.CountThis, parent.CountRight, parent.CountRight } )) //rotate right { } } else //!leftOf { if (SumIsPositive( new ulong[] { current.CountThis, current.CountRight, current.CountRight }, new ulong[] { parent.CountThis, parent.CountLeft, parent.CountLeft } )) //rotate left { } } } return(tree); } }