private void RemoveLeaf(int leaf)
{
if (leaf == m_root)
{
m_root = TreeNode.NULL_NODE;
return;
}
int parent = m_nodes[leaf].Parent;
int grandParent = m_nodes[parent].Parent;
int sibling;
if (m_nodes[parent].Child1 == leaf)
{
sibling = m_nodes[parent].Child2;
}
else
{
sibling = m_nodes[parent].Child1;
}
if (grandParent != TreeNode.NULL_NODE)
{
// Destroy parent and connect sibling to grandParent.
if (m_nodes[grandParent].Child1 == parent)
{
m_nodes[grandParent].Child1 = sibling;
}
else
{
m_nodes[grandParent].Child2 = sibling;
}
m_nodes[sibling].Parent = grandParent;
FreeNode(parent);
// Adjust ancestor bounds.
int index = grandParent;
while (index != TreeNode.NULL_NODE)
{
index = Balance(index);
int child1 = m_nodes[index].Child1;
int child2 = m_nodes[index].Child2;
m_nodes[index].AABB.Combine(m_nodes[child1].AABB, m_nodes[child2].AABB);
m_nodes[index].Height = 1 + MathUtils.Max(m_nodes[child1].Height, m_nodes[child2].Height);
index = m_nodes[index].Parent;
}
}
else
{
m_root = sibling;
m_nodes[sibling].Parent = TreeNode.NULL_NODE;
FreeNode(parent);
}
// validate();
}