二叉搜索树的创建的遍历
by:kvew www.smatrix.org/bbs http://blog.csdn.net/kvew/
#include<stdio.h>
#include<stdlib.h>
typedef struct BST* tree_pointer; //定义数据类型
typedef struct BST{
int key;
tree_pointer left;
tree_pointer right;
}BST;
tree_pointer CreateBST(tree_pointer root, int data){ // 创建一个根
root = (tree_pointer)malloc(sizeof(BST));
root->key = data;
root->left = NULL;
root->right = NULL;
return root;
}
tree_pointer InsertBST(tree_pointer root, int data){ // 元素插入函数
tree_pointer ptr,temp;
ptr = root;
if(ptr->key == data){ // 判断是否和当前结点的key相同
printf("This data is aready in this tree!/n"); //相同则提示,并退出程序
exit(1);
}
if(data < ptr->key){ // 如果比当前结点的key小,放到左子树上
if(ptr->left == NULL){ // 若左子树为空,那么将其插到左子树上
temp = (tree_pointer)malloc(sizeof(BST));
temp->key = data;
temp->left = NULL;
temp->right = NULL;
ptr->left = temp;
return root;
}
else{ //不为空,则继续向下查找
ptr = ptr->left;
InsertBST(ptr,data); //递归调用
return root; //此处记得返回root
}
}
else{ //如果比当前结点key大,放到右子树上
if(ptr->right == NULL){
temp = (tree_pointer)malloc(sizeof(BST)); //当前右子树为空则插入
temp->key = data;
temp->left = NULL;
temp->right = NULL;
ptr->right = temp;
return root;
}
else{ //不为空,则继续向下查找
ptr = ptr->right;
InsertBST(ptr,data); //递归调用
return root; //记得此处返回root
}
}
return NULL;
}
void preorder(tree_pointer ptr){ //前序遍历
if(ptr){
printf("%d ",ptr->key);
preorder(ptr->left);
preorder(ptr->right);
}
}
void postorder(tree_pointer ptr){ //后序遍历
if(ptr){
postorder(ptr->left);
postorder(ptr->right);
printf("%d ",ptr->key);
}
}
void inorder(tree_pointer ptr){ //中序遍历,对于BST,也就是从小到大打印出来了
if(ptr){
inorder(ptr->left);
printf("%d ",ptr->key);
inorder(ptr->right);
}
}
int main(){
int data = 0;
tree_pointer root;
root = NULL;
printf("Please input a number to root:/n");
scanf("%d",&data);
root = CreateBST(root,data);
printf("Now you can input others:/n");
scanf("%d",&data);
while(data != -1){
root = InsertBST(root,data);
scanf("%d",&data);
}
preorder(root);
printf("/n");
postorder(root);
printf("/n");
inorder(root);
printf("/n");
return 0;
}