简体   繁体   中英

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?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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