private void Rebuild() { if (isInSync) { return; } if (items.Count > 0) { root = new IntervalTreeNode <TKey, TValue>(items, comparer); } else { root = new IntervalTreeNode <TKey, TValue>(comparer); } isInSync = true; }
/// <summary> /// Initializes a node with a list of items, builds the sub tree. /// </summary> /// <param name="items">The items that should be added to this node</param> /// <param name="comparer">The comparer used to compare two items.</param> public IntervalTreeNode(IList <RangeValuePair <TKey, TValue> > items, IComparer <TKey> comparer) { this.comparer = comparer ?? Comparer <TKey> .Default; // first, find the median var endPoints = new List <TKey>(items.Count * 2); foreach (var item in items) { endPoints.Add(item.From); endPoints.Add(item.To); } endPoints.Sort(this.comparer); // the median is used as center value if (endPoints.Count > 0) { Min = endPoints[0]; center = endPoints[endPoints.Count / 2]; Max = endPoints[endPoints.Count - 1]; } var inner = new List <RangeValuePair <TKey, TValue> >(); var left = new List <RangeValuePair <TKey, TValue> >(); var right = new List <RangeValuePair <TKey, TValue> >(); // iterate over all items // if the range of an item is completely left of the center, add it to the left items // if it is on the right of the center, add it to the right items // otherwise (range overlaps the center), add the item to this node's items foreach (var o in items) { if (this.comparer.Compare(o.To, center) < 0) { left.Add(o); } else if (this.comparer.Compare(o.From, center) > 0) { right.Add(o); } else { inner.Add(o); } } // sort the items, this way the query is faster later on if (inner.Count > 0) { if (inner.Count > 1) { inner.Sort(this); } this.items = inner.ToArray(); } else { this.items = null; } // create left and right nodes, if there are any items if (left.Count > 0) { leftNode = new IntervalTreeNode <TKey, TValue>(left, this.comparer); } if (right.Count > 0) { rightNode = new IntervalTreeNode <TKey, TValue>(right, this.comparer); } }
public void Clear() { root = new IntervalTreeNode <TKey, TValue>(comparer); items = new List <RangeValuePair <TKey, TValue> >(); isInSync = true; }