二叉排序树,详细概念略过,参考数据结构书籍;详细代码如下:(以下代码,均可直接运行)
存储结构:二叉链表
typedef struct SOSTree {
int data;
struct SOSTree *LChild, *RChild;
} SOSTree;
插入:
bool InsertBST(SOSTree **T, int elem) {
// 二级指针,这样一来T可以在主函数中初始化为NULL,也能正常访问
SOSTree **p, *s;
p = (SOSTree **) malloc(sizeof(SOSTree *));
if (!SearchBST(*T, elem, NULL, p)) {
s = (SOSTree *) malloc(sizeof(SOSTree));
s->data = elem;
s->RChild = s->LChild = NULL;
if (!*T) *T = s;
else if (LTI(elem, (**p).data)) (**p).LChild = s;
else (**p).RChild = s;
return true;
}
return false;
}
查找:
bool SearchBST(SOSTree *T, int key, SOSTree *S, SOSTree **p) {
// p 用与在函数之间传递指针变量,因此使用二级指针
// 默认没有两个相同