KdTree节点删除

时间:2011-11-01 18:20:26

标签: algorithm data-structures kdtree

我一直在尝试从头开始实施KdTree。成功实现了add-后,在范围方法中查找最近的邻居和查找节点,我现在停留在删除节点上。

维基百科上描述的方法含糊不清,毫无用处。相反,我使用these slides作为起点。但是,幻灯片13上删除方法的描述让我感到困惑:

KDNode remove ( KDNode t , Point p , int cd ) {
if ( t == null ) return null;
else if (p.cd < t.data) t.left = remove (t.left , p , cd +1);
else if (p.cd > t.data) t.right = remove (t.right , p , cd +1);
else {
  if (t.right == null && t.left == null ) return null ;
  if (t.right != null )
    t.data = findmin(t.right , cd , cd +1);
  else {
    t.data = findmin (t.left , cd , cd +1);
    t.left = null;
}

t.right = remove (t.right , t . data , cd +1);
return t ;
}}

t.left替换为nullt.right with remove(t.right, ...)都毫无意义。

这是正确的吗?虽然我们处于此问题,但这种方法还有什么问题吗?应该注意的是,与这些幻灯片中描述的方法相反,我将相等的节点放在左边而不是右边。方法仍然有效吗?

1 个答案:

答案 0 :(得分:2)

删除非叶子的节点时,必须使用其中一个子树的叶节点替换它。这意味着叶子节点父节点需要获得一个NULL指针,叶子节点本身需要将其指针设置为被替换节点中的那些值。

您需要替换节点,因为子节点都没有使用正确的拆分轴,因此如果子树更改级别,则子树无效。最小正确值或最大左值仍然会将点划分为相同的轴,因此可以用于替换。