#include <stdio.h>
#include <stdlib.h>
typedef struct BiNode{
int data;
BiNode *lchild, *rchild;
};
bool searchBST(BiNode *T, int key, BiNode **it) {
if(!T) {
//(*it) = NULL;
return false;
}
else {
if(key > T->data)
{
*it=T;
searchBST(T->rchild, key, it);
}
else if(key < T->data)
{
*it=T;
searchBST(T->lchild, key, it);
}
else if(key == T->data) {
it = &T;
return true;
}
}
}
bool insert(BiNode **T, int key) {
BiNode *it, *s;
BiNode *root=*T;
if(!searchBST(root, key, &it)) {
s = (BiNode*)malloc(sizeof(BiNode));
s->data = key;
printf("%d ",s->data);
s->lchild = NULL;
s->rchild = NULL;
if(!it) {
*T = s;
}
else if(key > it->data) {
it->rchild = s;
}
else if(key < it->data) {
it->lchild = s;
}
return true;
}
else {
return false;
}
}
void print(BiNode *T) {
if(T) {
print(T->lchild);
printf("%d ", T->data);
print(T->rchild);
}
// else
// printf("it's a empty tree/n");
}
int main() {
int i, key, length;
bool status;
BiNode *T = NULL;
printf("input numbers of key/n");
scanf("%d", &length);
for( i=0; i<length; i++) {
scanf("%d", &key);
status = insert(&T, key);
//printf("%d/n", status);
}
printf("come/n");
print(T);
getchar();
getchar();
return 1;
}
二叉排序樹的C代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.