二叉排序树是一种特殊的二叉树,其左子树上所有节点的值小于根节点值,右子树上所有节点的值大于根节点值。通过构建二叉排序树并进行中序遍历,可以得到一个有序序列。
(1)定义数据结构:
a. 定义顺序表结构 SqTable,包含一个存储记录的数组 r 和一个表示长度的变量 length;
b. 定义二叉树节点结构 BiTNode,包含记录数据、左子节点指针和右子节点指针。
(2)插入操作(Insert_BST):
a. 若树为空,将新节点作为根节点插入。
b. 否则,从根节点开始比较,若新节点值小于当前节点值,则向左子树递归查找插入位置;否则向右子树递归查找。
c. 找到合适位置后,将新节点插入到父节点的左子树或右子树。
(3)中序遍历(InOrder):
对二叉树进行中序遍历,将遍历结果依次存入顺序表中。中序遍历二叉排序树会得到一个按关键字有序的序列。
(4)排序函数(BSTSort):
a. 初始化一棵空的二叉排序树。
b. 遍历顺序表中的每个元素,依次插入到二叉排序树中。
c. 对构建好的二叉排序树进行中序遍历,将结果存回原顺序表,完成排序
#include <iostream>
#include"Stack_tree.h"
using namespace std;
typedef struct {
RcdType* r;
int length;
}SqTable;
//在以T为根指针的二叉排序树中插入记录e
void Insert_BST(BiTree &T,RcdType e)
{
BiTree p,f;
BiTree s = new BiTNode;
s->data = e;
s->lchild = NULL;
s->rchild = NULL;
if(!T) T=s;
else
{
p=T;
while(p)
if(e.key<p->data.key)
{
f=p;p=p->lchild;
}
else
{
f=p;p=p->rchild;
}
if(e.key<f->data.key)
f->lchild=s;
else
f->rchild=s;
}
}//Insert_BST
//中序遍历算法
void InOrder(BiTree T,SqTable &L,int &i)
{
if(T)
{
InOrder(T->lchild,L,i);
L.r[++i]=T->data;
InOrder(T->rchild,L,i);
}
}
//利用二叉排序树对顺序表L进行排序
void BSTSort(SqTable &L)
{
BiTree T=NULL;
int i;
for(i=1;i<=L.length;++i)
Insert_BST(T,L.r[i]);
i = 0;
InOrder(T,L,i);
}//BSTSort
int main() {
SqTable L;
L.length = 6;
L.r = new RcdType[L.length + 1]; // 分配内存,下标从1开始
int i;
KeyType keys[] = {7, 3, 1, 5, 8, 6};
InfoType infos[] = {'G', 'C', 'A', 'E', 'H', 'F'};
for (i = 1; i <= L.length; ++i) {
L.r[i].key = keys[i - 1];
L.r[i].info = infos[i - 1];
}
cout << "排序前的顺序表:";
for (i = 1; i <= L.length; ++i) {
cout << "(" << L.r[i].key << ", " << L.r[i].info << ") ";
}
cout << endl;
BSTSort(L); // 利用二叉排序树对顺序表进行排序
cout << "排序后的顺序表:";
for (i = 1; i <= L.length; ++i) {
cout << "(" << L.r[i].key << ", " << L.r[i].info << ") ";
}
cout << endl;
delete[] L.r; // 释放内存
return 0;
}
结果如下
排序前的顺序表:(7, G) (3, C) (1, A) (5, E) (8, H) (6, F)
排序后的顺序表:(1, A) (3, C) (5, E) (6, F) (7, G) (8, H)
--------------------------------
Process exited after 0.5975 seconds with return value 0
请按任意键继续. . .
&spm=1001.2101.3001.5002&articleId=151224644&d=1&t=3&u=220d11871b234cc58bd5b9ecf064561b)
5001

被折叠的 条评论
为什么被折叠?



