二叉搜索树的创建及其遍历

来源:互联网 发布:mac系统入门教程 编辑:程序博客网 时间:2024/05/19 23:15
#include <iostream>
using namespace std;
//树的结构体
typedef struct node{
char data;
struct node *left, *right;
}*ptree,pnode;


//搜索二叉树的根节点
ptree creategen(char c)
{
ptree t;
t = (ptree)malloc(sizeof(pnode));
t->data = c;
t->left = NULL;
t->right = NULL;
return t;
}


//创建搜索二叉树
void create(ptree root, char c)
{
ptree temp,t;
t = root;
if (t->data == c)
{
printf("你所输入的元素已经存在:\n");
exit(1);
}
if (c < t->data)
{
if (t->left == NULL)
{
temp = (ptree)malloc(sizeof(pnode));
temp->data = c;
temp->left = NULL;
temp->right = NULL;
t->left = temp;
}
else
{
create(t->left, c);
}
}
if (c > t->data)
{
if (t->right == NULL)
{
temp = (ptree)malloc(sizeof(pnode));
temp->data = c;
temp->left = NULL;
temp->right = NULL;
t->right= temp;
}
else
{
create(t->right, c);
}
}
return;
}


//递归先序遍历二叉树
void preorder(ptree t)
{
if (t)
{
printf("%c",t->data);
preorder(t->left);
preorder(t->right);
}
}


//递归中序遍历二叉搜索树
void mindorder(ptree t)
{
if (t)
{
mindorder(t->left);
printf("%c",t->data);
mindorder(t->right);
}
}


//递归后序遍历二叉搜索树
void aftorder(ptree t)
{
if (t)
{
aftorder(t->left);
aftorder(t->right);
printf("%c",t->data);
}
}


int main()
{
ptree bt;
int n;
char ch;
printf("创建二叉搜索树的根节点:\n");
scanf("%c", &ch);
getchar();
bt = creategen(ch);
printf("输入二叉树的子节点数:\n");
scanf("%d",&n);
getchar();
while (n--)
{
scanf("%c", &ch);
getchar();
create(bt,ch);
}
printf("先序遍历二叉搜索树是:\n");
preorder(bt);
printf("\n");
printf("中序遍历二叉搜索树是:\n");
mindorder(bt);
printf("\n");
printf("后序遍历二叉搜索树是\n");
aftorder(bt);
printf("\n");
return 0;
}
0 0
原创粉丝点击