void Insert(int triangleIndex)
{
//Insertions can easily be performed stacklessly.
//Only one path is chosen at each step and nothing is returned, so the history of the 'recursion' is completely forgotten.
var node = new LeafNode(triangleIndex, data);
if (root == null)
{
//Empty tree. This is the first and only node.
root = node;
}
else
{
if (root.IsLeaf) //Root is alone.
root.TryToInsert(node, out root);
else
{
//The caller is responsible for the merge.
BoundingBox.CreateMerged(ref node.BoundingBox, ref root.BoundingBox, out root.BoundingBox);
Node treeNode = root;
while (!treeNode.TryToInsert(node, out treeNode)) ;//TryToInsert returns the next node, if any, and updates node bounding box.
}
}
}