当前位置:网站首页>在二叉排序树中删除节点
在二叉排序树中删除节点
2022-07-23 05:46:00 【菠菠萝宝】
前言
在二叉排序树中删除节点的算法一直不是很明白,感觉很绕,花了三个小时算是彻底弄懂了。分享一下自己的心得。
个人在学习数据结构与算法中,有时候不理解的地方看别人的代码也是看不懂,自己的思路想要保存下来,比较清晰。
个人是个菜鸟,写的代码都很菜,希望大家不要介意。
代码如下
//二叉排序树的删除
Node* DeleteNode(BSTree bt, ElemType key) {
if (bt == NULL) {
return NULL;
}
//p指针保存当前节点。
Node* p = bt;
//pre指针保存p的父节点,方便后面指向p节点的做华子或右孩子
Node* pre = NULL;
//先在二叉搜索树中找到值为key的节点
while (p != NULL) {
if (p->data == key) {
break;
}
else if (key < p->data) {
pre = p;//保存p的前驱
p = p->lchild;
}
else {
pre = p;//保存p的前驱
p = p->rchild;
}
}
//如果没有找到,p指针为空,则返回根节点
if (p == NULL) {
return bt;
}
//当p指向的节点的左孩子为空时,将p节点的右孩子赋给p的父节点。
if (p->lchild == NULL) {
Node* temp = p;
//三元表达式为判断p为pre的左孩子还是右孩子
(pre->data < p->data ? pre->rchild : pre->lchild) = p->rchild;
free(temp);
temp = NULL;
}
//当p指向的节点的右孩子为空时,将p节点的左孩子赋给p的父节点。
else if (p->rchild == NULL) {
Node* temp = p;
//三元表达式为判断p为pre的左孩子还是右孩子
(pre->data < p->data ? pre->rchild : pre->lchild) = p->lchild;
free(temp);
temp = NULL;
}
//当左右孩子均不为空时,此处采用删除节点的左子树的最大值为替换。
else {
//post指针初始指向当前节点。实为max的父节点。
Node* post = p;
//max指针来找当前节点左子树的最大值。
Node* max = p->lchild;
//最后找下来max->rchild必为空。
while (max->rchild != NULL) {
post = max;
max = max->rchild;
}
//将最大值替换删除节点。
p->data = max->data;
//处理最大值节点的后续子节点。
//当post指针没有变时,说明最大节点就是post节点(也就是待删除节点p)的左孩子。那么对后续节点的处理就是直接把max的左孩子赋给post节点的左孩子(因为max节点的右孩子为空)。
if (post == p) {
post->lchild = max->lchild;
}
//当post指针和待删除节点p不同时,说明max在post的右子树里。那么对后续节点的处理就是直接把max的左孩子赋给post节点的右孩子(因为max节点的右孩子为空)。
else {
post->rchild = max->lchild;
}
//因为待删除节点已经被max的值覆盖了,max的孩子也已经被处理了,现在的max已经是没用的节点了,要free掉。
free(max);
}
return bt;
}
边栏推荐
猜你喜欢

Unity3d:UGUI,UI与特效粒子层级,2018.2以上版本BakeMesh,粒子在两个Image之间且在ScrollView

HCIP---BGP相关配置(联邦篇)

Common sort -- merge sort (recursive and non recursive) + count sort

Instant messaging websocket

【无标题】

Unity3d+GameFramework:资源分析,资源依赖,循环依赖检测

MySQL性能优化,索引优化

C #: TOPK: take the largest 100 before 10000 numbers, and sort the heap

LSM-tree(Log Structured-Merge Tree)的理解

HCIP---MGRE综合实验
随机推荐
unity3d:UGUI源码EventSystem输入系统常见问题
C (CSharp) wechat official account development - basic configuration
PDF在线预览,pdf.js的使用
【无标题】
Unity3d:ugui source code eventsystem input system FAQ
第五周作业
深入解析Redis中的复制
OSPF routing strategy and Traffic Capture
Analysis of UDP protocol and TCP protocol
Unity3d:UGUI,UI与特效粒子层级,2018.2以上版本BakeMesh,粒子在两个Image之间且在ScrollView
HCIP---GRE协议和MGRE环境,以及OSPF协议的相关知识点
flask项目celery使用redis sentinel中遇到的坑
C# 自定义Queue队列集合
Common sort -- merge sort (recursive and non recursive) + count sort
剖析Redis服务器
Explain TCP segmentation and IP fragmentation in detail
C # custom stack
Explain the interactive data flow and block data flow of TCP in detail
Explain the establishment of TCP connection in detail
Hcip--- BGP related configuration