7.3.1二叉排序树
代码实现
#pragma once
#include <iostream>
using namespace std;
typedef int KeyType;
typedef int InfoType;
#define ENDFLAG 2021
typedef struct
{
KeyType key;
InfoType otherinfo;
}ElemType;
typedef struct BSTNode
{
ElemType data;
struct BSTNode* lchild, * rchild;
}BSTNode,*BSTree;
void InsertBST(BSTree& T, ElemType e)
{
if (!T)
{
BSTNode* S = new BSTNode;
S->data = e;
S->lchild = S->rchild = NULL;
T = S;
}
else if (e.key < T->data.key)
{
InsertBST(T->lchild, e);
}
else if (e.key > T->data.key)
{
InsertBST(T->rchild, e);
}
}
void CreateBST(BSTree& T)
{
T = NULL;
ElemType e;
cin >> e.key;
while (e.key != ENDFLAG)
{
InsertBST(T, e);
cin >> e.key;
}
}
void InOrderTraverse(BSTree T)
{
if (T)
{
InOrderTraverse(T->lchild);
cout << T->data.key <<" ";
InOrderTraverse(T->rchild);
}
}
BSTree SearchBST(BSTree T, KeyType key)
{
if ((!T) || key == T->data.key)
{
return T;
}
else if (key < T->data.key)
{
return SearchBST(T->lchild, key);
}
else
{
return SearchBST(T->rchild, key);
}
}
void DeleteBST(BSTree& T, KeyType key)
{
BSTNode* p = T;
BSTNode* f = NULL;
BSTNode* q;
BSTNode* s;
while (p)
{
if (p->data.key == key)
{
break;
}
f = p;
if (p->data.key > key)
{
p = p->lchild;
}
else
{
p = p->rchild;
}
}
if (!p)
{
return;
}
q = p;
if ((p->lchild) && (p->rchild))
{
s = p->lchild;
while (s->rchild)
{
q = s;
s = s->rchild;
}
p->data = s->data;
if (q != p)
{
q->rchild = s->lchild;
}
else
{
q->lchild = s->lchild;
}
delete s;
return;
}
else if (!p->rchild)
{
p = p->lchild;
}
else if (!p->lchild)
{
p = p->rchild;
}
if (!f)
{
T = p;
}
else if (q == f->lchild)
{
f->lchild = p;
}
else
{
f->rchild = p;
}
delete q;
}
int main()
{
BSTree T;
cout << "请输入若干字符,用回车区分,以2021结束输入" << endl;
CreateBST(T);
cout << "当前有序二叉树中序遍历结果为" << endl;
InOrderTraverse(T);
cout << endl;
KeyType key;
cout << "请输入待查找关键字:";
cin >> key;
BSTree result = SearchBST(T, key);
if (result)
{
cout << "找到关键字:" << key << endl;
}
else
{
cout << "未找到关键字:" << key << endl;
}
cout << "请输入待删除的关键字:";
cin >> key;
DeleteBST(T, key);
cout << "当前有序二叉树中序遍历结果为" << endl;
InOrderTraverse(T);
cout << endl;
system("pause");
return 0;
}
运行结果
