二叉排序树又叫二叉查找树,英文名称是:Binary Sort Tree. BST的定义就不详细说了,我用一句话概括:左 < 中 < 右。 根据这个原理,我们可以推断:BST的中序遍历必定是严格递增的。
在建立一个BST之前,大家可以做一下这个题目(很简单的):
已知,某树的先序遍历为:4, 2, 1 ,0, 3, 5, 9, 7, 6, 8. 中序遍历为: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 请画出该树。
我们知道,树的基本遍历有4种方式,分别是:
先序遍历;中序遍历;后续遍历;层次遍历。事实上,知道任意两种方式,并不能唯一地确定树的结构,但是,只要知道中序遍历和另外任意一种遍历方式,就一定可以唯一地确定一棵树,于是,上面那个题目的答案如下:
using namespace std;
// BST的结点
typedef struct node
{
int key;
struct node *lChild, *rChild;
}Node, *BST;
// 在给定的BST中插入结点,其数据域为element, 使之称为新的BST
bool BSTInsert(Node * &p, int element)
{
if (p == NULL)
{
p = new Node;
p->key = element;
p->lChild = p->rChild = NULL;
}
if (element == p->key)
{
return false;
}
if (element < p->key)
{
BSTInsert(p->lChild, element);
}
else
BSTInsert(p->rChild, element);
return true;
}
void PrintBST(BST &p, int depth)
{
int i;
if (p->rChild)
PrintBST(p->rChild, depth + 1);
for (i = 1; i <= depth; i++)
printf(" ");
printf("%d\n", p->key);
if (p->lChild)
PrintBST(p->lChild, depth + 1);
}
void createBST(BST &p)
{
int t;
int depth = 0;
p = NULL;
printf("\n请输入关键字(以-123结束建立平衡二叉树):");
scanf("%d", &t);
while (t != -123)
{
BSTInsert(p, t);
printf("\n请输入关键字(以-123结束建立平衡二叉树):");
scanf("%d", &t);
}
printf("\n****************************************************\n");
printf(" 您创建的二叉树为\n");
if (p)
PrintBST(p, depth);
else
printf("这是一棵空树!\n");
}
BST search(BST &p, int key)
{
if (p == NULL)
return NULL;
else if (key == p->key)
{
printf("查找成功!,%d的地址是%p\n", key, p);
return p;
}
else if (key < p->key)
search(p->lChild, key);
else
search(p->rChild, key);
}
//先序遍历
void preorderBST(BST p)
{
if (p)
{
cout << p->key << " ";
preorderBST(p->lChild);
preorderBST(p->rChild);
}
}
//中序遍历(这个可以做为排序算法)//后面的堆排序需要用到这种方法
void inorderBST(BST p)
{
if (p)
{
inorderBST(p->lChild);
cout << p->key << " ";
inorderBST(p->rChild);
}
}
int main(void)
{
int ch;
BST T;
printf("请写入您要建立的BST树的所有结点值!\n");
createBST(T);
while (1)
{
printf("按下列选项选择您要进行的操作\n");
printf("1前序输出.\n");
printf("2.中序输出\n");
printf("3.查找\n");
printf("4.退出\n");
scanf("%d", &ch);
switch (ch)
{
case 1:
preorderBST(T); break;
case 2:
inorderBST(T); break;
case 3:
{
int m;
printf("您要查找的是多少呢?\n");
scanf("%d", &m);
search(T, m);
}
break;
case 4:
return 0; break;
default:
break;
}
}
return 0;
}
实验结果: