public void Insert(Segment segment)
 {
     if (_root == null)
     {
         _root = new SegmentTreeNode() { Range = segment.Range, Names = new List<string>() { segment.Name } };
     }
     else
     {
         DoInsert(_root, segment);
     }
 }
 private SegmentTreeNode RotateRight(SegmentTreeNode grandParent, SegmentTreeNode parent, SegmentTreeNode leftChild)
 {
     if (null != grandParent)
     {
         grandParent.Right = leftChild;
     }
     else
     {
         _root = leftChild;
     }
     parent.Left = leftChild.Right;
     leftChild.Right = parent;
     return grandParent;
 }
 private void RotateLeft(SegmentTreeNode grandParent, SegmentTreeNode parent, SegmentTreeNode rightChild)
 {
     if (null != grandParent)
     {
         grandParent.Right = rightChild;
     }
     else
     {
         _root = rightChild;
     }
     parent.Right = rightChild.Left;
     rightChild.Left = parent;
 }
        private void DoInsert(SegmentTreeNode top, Segment segment)
        {
            var compareResult = segment.Range.CompareTo(top.Range);

            if (compareResult < 0)
            {
                AddLeftLeaf(top, segment);
            }
            else if (compareResult > 0)
            {
                AddRightLeaf(top, segment);
            }
            else
            {
                var intersection = RangeComparer.Intersect(top.Range, segment.Range);

                top.Range = intersection.Intersection;
                top.Names.Add(segment.Name);

                if (intersection.LeftSetDifference != null)
                {
                    AddLeftLeaf(top, new Segment() { Range = intersection.LeftSetDifference, Name = segment.Name });
                }
                if (intersection.RightSetDifference != null)
                {
                    AddRightLeaf(top, new Segment() { Range = intersection.RightSetDifference, Name = segment.Name });
                }
            }
        }
 public BinarySegmentTree()
 {
     _root = null;
 }
        private SegmentTreeNode DoFind(SegmentTreeNode top, long ip)
        {
            var compareResult = top.Range.CompareTo(ip);

            if (compareResult == 0)
            {
                return top;
            }
            else if (compareResult > 0 && top.Left != null)
            {
                return DoFind(top.Left, ip);
            }
            else if (compareResult < 0 && top.Right != null)
            {
                return DoFind(top.Right, ip);
            }
            return null;
        }
 private void AddRightLeaf(SegmentTreeNode top, Segment segment)
 {
     if (top.Right == null)
     {
         top.Right = new SegmentTreeNode()
         {
             Range = segment.Range,
             Names = new List<string>() { segment.Name }
         };
     }
     else
     {
         DoInsert(top.Right, segment);
     }
 }