算法:二叉排序树的删除节点策略及其图形化(二叉树查找)

本文介绍了二叉排序树(BST)的删除节点操作,包括叶子节点、单子树节点和双子树节点的删除策略。删除时,通常会寻找待删除节点的直接前驱或后继节点进行替换。文章还提及了保持二叉排序树平衡的重要性,提到AVL树作为平衡二叉排序树的一种,其左右子树高度差最多为1,以确保高效查找。
摘要由CSDN通过智能技术生成

二叉排序树(BST,Binary Sort Tree)具有这样的性质:对于二叉树中的任意节点,如果它有左子树或右子树,则该节点的数据成员大于左子树所有节点的数据成员,且小于右子树所有节点的数据成员。排序二叉树的中序遍历结果是从小到大排列的。

二叉排序树的查找和插入比较好理解,主要来看一下删除时的情况。

如果需要查找并删除如图8-6-8中的37, 51, 73,93这些在二叉排序树中是叶子的结点,那是很容易的,毕竟删除它们对整棵树来说,其他结点的结构并未受到影响。


对于要删除的结点只有左子树或只有右子树的情况,相对也比较好解决。那就是结点删除后,将它的左子树或右子树整个移动到删除结点的位置即可,可以理解为独子继承父业。比如图8-6-9,就是先删除35和99两结点,再删除58结点的变化图,最终,整个结构还是一个二叉排序树。


但是对于要删除的结点既有左子树又有右子树的情况怎么办呢?比如图8-6-10中的47结点若要删除了,它的两儿子和子孙们怎么办呢?


前人总结的比较好的方法就是,找到需要删除的结点p的直接前驱(或直接后继)s,用s来替换结点p,然后再删除此结点s,如图8-6-12所示。

注意:这里的前驱和后继是指中序遍历时的顺序。


Deletion

There are three possible cases to consider:

Deleting a leaf (node with no children): Deleting a leaf is easy, as we can simply remove it from the tree.

Deleting a node with one child: Remove the node and replace it with its child.

Deleting a node with two children: Call the node to be deleted N. Do not delete N. Instead, choose either its in-order successor node or its in-

order predecessor node, R. Replace the value of N with the value of R, then delete R.

As with all binary trees, a node's in-order successor is the left-most child of its right subtree, and a node's in-order predecessor is the right-most 

child of its left subtree. In either case, this node will have zero or one children. Delete it according to one of the two simpler cases above.


下面来看代码:(参考《linux c 编程一站式学习》

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*************************************************************************
    > File Name: binarysearchtree.h
    > Author: Simba
    > Mail: dameng34@163.com
    > Created Time: Sat 29 Dec 2012 06:05:55 PM CST
 ************************************************************************/


#ifndef BST_H
#define BST_H

typedef  struct node *link;
struct node
{
     unsigned  char item;
    link left, right;
};

link search(link t,  unsigned  char key);
link insert(link t,  unsigned 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值