二叉排序树:
又称二叉查找树,或是一棵空树,其具有的性质如下:
1)若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值。
2)若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值。
3)左右子树本身也分别为二叉排序树。
一棵二叉排序树一定是二叉树,按中序遍历二叉排序树,所得到的中序遍历序列是一个递增有序序列。
其实现的代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node
{
datatype key;
struct node *lchild, *rchild;
}bsnode;
typedef bsnode *bstree;
// Binary sort tree insertion operation.
void insertbstree(bstree *t, datatype x)
{
bstree f, p;
p = *t;
while(p) //find the insert position.
{
if(x==p->key)return; //if the binary sort tree t has have key, need not insert.
f = p; // f is used to save final insertion positionthe that new node will insert.
p = (x < p->key)? p->lchild:p->rchild;
}
p = (bstree)malloc(sizeof(bsnode));
p->key = x;
p->lchild = p->rchild = NULL;
if(*t == NULL) *t = p;
else
if(x < f->key)
f->lchild = p;
else
f->rchild = p;
}
//According to the input node seqlist, building a binary sort tree, and return the root node address.
bstree createbstree(void)
{
bstree t = NULL;
datatype key;
printf("please input a Node seqlist that with -1 for end:\n");
scanf("%d", &key);
while(key != -1)
{
insertbstree(&t, key);
scanf("%d", &key);
}
return t;
}
// in_order for binary sort tree.
void inorder(bstree t)
{
if(t)
{
inorder(t->lchild);
printf("%4d",t->key);
inorder(t->rchild);
}
}
// A Non-recursive search for binary sort tree
void bssearch1(bstree t, datatype x, bstree *p, bstree *q)
{
*p = NULL;
*q = t;
while(*q)
{
if(x == (*q)->key) return;
*p = *q;
*q = (x < (*q)->key)?(*q)->lchild:(*q)->rchild;
}
return;
}
// A recursive search for binary sort tree
bstree bssearch2(bstree t, datatype x)
{
if(t == NULL || x == t->key) return t;
if(x < t->key)
return bssearch2(t->lchild, x);
else
return bssearch2(t->rchild, x);
}
void main()
{
bstree p, q;
datatype x;
bstree t;
t = createbstree();
inorder(t);
printf("\nPlease input a node key that will be inserted:");
scanf("%d",&x);
insertbstree(&t, x);
inorder(t);
printf("\n Please input a Node key that need to search:");
scanf("%d", &x);
bssearch1(t, x, &p, &q);
if(q) printf("\nFound\n");
else printf("\nNot Found\n");
printf("\n Please input a Node key that need to search:");
scanf("%d", &x);
q = bssearch2(t, x);
if(q) printf("\nFound\n");
else printf("\nNot Found\n");
}