算法思想:先序遍历二叉树,如果当前结点等于x,则删除他的左子树;如果当前结点大于x,则递归查找他的左子树中小于x的结点进行删除;如果当前结点小于x,则删除他的左子树并删除当前结点,然后递归查找他右子树中小于x的结点进行删除。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElemType;
typedef struct BSTNode {
ElemType data;
struct BSTNode* lchild;
struct BSTNode* rchild;
}BSTNode, * BSTree;
//中序遍历
void inOrder(BSTree T) {
if (T != NULL) {
inOrder(T->lchild);
printf("%c", T->data);
inOrder(T->rchild);
}
}
//插入操作
void insertBSTree(BSTree& T, ElemType num) {
if (T == NULL) {
T = (BSTNode*)malloc(sizeof(BSTNode));
T->data = num;
T->lchild = NULL;
T->rchild = NULL;
}
else if (T->data < num) {
insertBSTree(T->rchild, num);
}
else if (T->data > num) {
insertBSTree(T->lchild, num);
}
}
//创建二叉排序树
BSTree creatBSTree() {
ElemType num;
BSTNode* T = NULL;
while (scanf("%c", &num) && num != '\n') {
insertBSTree(T, num);
}
return T;
}
/*算法思想:先序遍历二叉树,如果当前结点等于x,则删除其左子树;如果当前结点小于x,先删除左子树,再删除根节点,并递归删除右子树中小于x的结点;
如果当前结点大于x,则递归删除左子树中小于x的结点*/
void delectoperate(BSTNode*& T) {
if (T != NULL) {
delectoperate(T->lchild);//删除左子树
T->lchild = NULL;//左孩子指针域置空
delectoperate(T->rchild);//删除右子树
T->rchild = NULL;//右孩子指针域置空
free(T);//删除根节点
T = NULL;//指针域置空
}
}
void delect(BSTree &T, ElemType x)
{
if (T != NULL) {
if (T->data == x) {
delectoperate(T->lchild);
}
else if (T->data < x) {
delectoperate(T->lchild);
BSTNode* pnode = T;
T = T->rchild;
delect(T, x);
free(pnode);
pnode = NULL;
}
else {
delect(T->lchild, x);
}
}
}
int main() {
BSTree T = creatBSTree();
/*inOrder(T);
printf("\n");*/
ElemType x;
scanf("%c", &x);//输入要删除元素
delect(T, x);
inOrder(T);
return 0;
}