这里又叫做二叉搜索树
代码:
//二叉排序树(二叉搜索树Binary Search Tree)
//杨鑫
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int key;
struct node *lchild, *rchild;
}BSTNode, *BSTree;
//插入
int InsertBST(BSTree *bst, int k)
{
BSTree r, s, pre;
r = (BSTree)malloc(sizeof(BSTNode));
r->key = k;
r->lchild = NULL;
r->rchild = NULL;
if(*bst == NULL)
{
*bst = r;
return 1;
}
pre = NULL;
s = *bst;
while(s)
{
if(k == s->key)
return 0;
else if(k < s->key)
{
pre = s;
s = s->lchild;
}
else
{
pre = s;
s = s->rchild;
}
}
if(k < pre->key)
pre->lchild = r;
else
pre->rchild = r;
return 1;
}
void CreateBST(BSTree *bst)
{
int key;
*bst = NULL;
scanf("%d",