c++treebinary-search-tree

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?


Solution

  • Yes, you don't want to copy the node, you just want to "move" it (i.e., 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).