简体   繁体   English

二进制搜索树删除而无需复制

[英]Binary Search Tree deletion without copying

When programming a simple binary search tree data structure (non self-balancing), the advice most resources give when deleting a node with two children is to copy the data out of one of the left child to the node that is being deleted. 在对简单的二进制搜索树数据结构进行编程(非自平衡)时,大多数资源在删除具有两个子节点的节点时的建议是将数据从左子节点之一复制到要删除的节点。 Is this bad practice? 这是不好的做法吗? Wouldn't some sort of pointer manipulation provide faster results? 某种指针操作不会提供更快的结果吗? Is there a BST rotation algorithm that can generalize this? 有BST旋转算法可以将其概括吗?

Yes, you don't want to copy the node, you just want to "move" it (ie, change pointers around) to put it into the spot of the one you're deleting. 是的,您不想复制该节点,而只想“移动”它(即,更改指针)以将其放入要删除的节点的位置。 If you're not trying to maintain balance, you don't really need to do any kind of rotation though -- you just pick the right-most node in the left sub-tree (or the left-most node in the right sub-tree). 如果您不想保持平衡,则实际上并不需要进行任何轮换-您只需选择左侧子树中最右边的节点(或右侧子树中最左边的节点) -树)。 You delete that from its current place, and insert it into the place of the node you need to delete (all strictly by manipulating pointers). 您将其从当前位置删除,然后将其插入需要删除的节点的位置(所有操作都严格通过操作指针进行)。

Copying data has O(1) complexity vs. possible O(N) when manipulating pointers: the source node (the right-most node in the left sub-tree or the left-most node in the right sub-tree) may have one child and a sub-tree under it. 复制数据具有O(1)复杂度,而处理指针时可能具有O(N):源节点(左子树中最右边的节点或右子树中最左边的节点)可能只有一个子及其下的子树。 Unlike a single node insertion, merging sub-trees would be required in this case. 与单节点插入不同,在这种情况下将需要合并子树。 To avoid copying overhead, one should store pointers to objects rather than objects in BST. 为了避免复制开销,应该在BST中存储指向对象而不是对象的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM