#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define ARRAYLEN 10
int source[]={54,90,6,69,12,37,92,28,65,83};
typedef struct bst
{
int data;
struct bst *left;
struct bst *right;
}BSTree;
BSTree bst,*pos;
void InsertBST(BSTree *t,int key)
{
BSTree *p,*parent,*head;
if(!(p=(BSTree*)malloc(sizeof(BSTree))))
{
printf("shenqingshibai");
exit(0);
}
p->data=key;//新建p节点来保存数据 ,为31~34行赋值做准备
p->left=p->right=NULL;//新加的节点必定是叶子节点,没有孩子
head=t;
while(head)
{
parent=head;
if(key<head->data)
head=head->left;
else
head=head->right;
}
if(key<parent->data)
parent->left=p;
else
parent->right=p;
}
void CreateBST(BSTree *t,int data[],int n)
{
int i;
t->data=data[0];//为根节点赋值 ,data[0]即为主函数中source[0]
t->left=t->right=NULL;
for(i=0;i<n;i++)
{
InsertBST(t,data[i]);
}
}
BSTree *SearchBST(BSTree *t,int key)
{
if(!t||t->data==key)
return t;
else if(key>t->data)
return(SearchBST(t->right,key));
else
return(SearchBST(t->left,key));
}
void DLR(BSTree *t)
{
if(t)
{
//if(t==&bst)
printf("%d ",t->data);
//else
//printf(" ");
DLR(t->left);
DLR(t->right);
}
return;
}
void LDR(BSTree *t)
{
if(t)
{
LDR(t->left);
//if(t==&bst)
printf("%d ",t->data);
//else
//printf(" ");
LDR(t->right);
}
return;
}
void LRD(BSTree *t)
{
if(t)
{
LDR(t->left);
LDR(t->right);
//if(t==&bst)
printf("%d ",t->data);
//else
//printf(" ");
}
return;
}
int main()
{
int key;
CreateBST(&bst,source,ARRAYLEN);
printf("先序遍历:");
DLR(&bst);
printf("\n");
printf("中序遍历:");
LDR(&bst);
printf("\n");
printf("后序遍历:");
LRD(&bst);
printf("\n请输入关键字:");
scanf("%d",&key);
pos=SearchBST(&bst,key);
if(pos)
printf("查找成功,该节点地址为:%x\n",pos);
else
printf("查找失败\n");
getch();
return 0;
}
先序,中序,后序遍历
最新推荐文章于 2023-10-20 17:57:33 发布