CHAPTER 3. BINARY SEARCH TREE
22
3.3
Deletion
Removing a node from a BST is fairly straightforward, with four cases to con-
sider:
1.
the value to remove is a leaf node; or
2.
the value to remove has a right subtree, but no left subtree; or
3.
the value to remove has a left subtree, but no right subtree; or
4.
the value to remove has both a left and right subtree in which case we
promote the largest value in the left subtree.
There is also an implicit fifth case whereby the node to be removed is the
only node in the tree. This case is already covered by the first, but should be
noted as a possibility nonetheless.
Of course in a BST a value may occur more than once. In such a case the
first occurrence of that value in the BST will be removed.
23
14
31
7
9
#1:
Leaf Node
#2: Right subtree
no
left subtree
#3:
Left subtree
no right subtree
#4: Right subtree
and left subtree
Figure 3.2: binary search tree deletion cases
The
Remove algorithm given below relies on two further helper algorithms
named
F indP arent, and
F indN ode which are described in
Dostları ilə paylaş: