二叉树的基本操作,在建立的就出问题
程序代码:#include<stdio.h>
#include<stdlib.h>
#define QueueMaxsize 20
#define StackMaxsize 10
typedef struct BTreeNode // 构建一个二叉树
{
char data;
struct BTreeNode* left;
struct BTreeNode* right;
}caicai;
void init(caicai** BT) //初始化二叉树
{
*BT=NULL;
}
void Preorder(caicai *BT) //先序遍历,最先遍历根节点
{
if(BT!=NULL)
{
printf("%c ",BT->data);
Preorder(BT->left);
Preorder(BT->right);
}
}
void Inorder(caicai *BT) //先遍历左子树,再遍历根节点,最后遍历右子树
{
if(BT!=NULL)
{
Inorder(BT->left);
printf("%c ",BT->data);
Inorder(BT->right);
}
}
void Postorder(caicai *BT) //根节点在最后遍历
{
if(BT!=NULL)
{
Postorder(BT->left);
Postorder(BT->right);
printf("%c ",BT->data);
}
}
void Levelorder(caicai *BT) //按层遍历法,非递归
{
caicai *p,*q[QueueMaxsize];
int front=0,rear=0;
if(BT!=NULL)
{
rear=(rear+1)%QueueMaxsize;
q[rear]=BT;
}
while(front!=rear)
{
front=(front+1)%QueueMaxsize;
p=q[front];
printf("%c ",p->data);
}
if(p->left!=NULL)
{
rear=(rear+1)%QueueMaxsize;
q[rear]=p->left;
}
if(p->right!=NULL)
{
rear=(rear+1)%QueueMaxsize;
q[rear]=p->right;
}
}
void creat(caicai **BT,char *a)
{
caicai *p,*s[StackMaxsize];
int top=-1,k,i=0;
*BT=NULL;
while(a[i])
{
switch(a[i])
{
case' ':break;
case'(':
if(top==StackMaxsize-1)
{
printf("The stack is too small!\n");
exit(1);
}
top++;
s[top]=p;
k=1;
break;
case')':
if(top==-1)
{
printf("Error!\n");
exit(1);
}
top--;
break;
case',':
k=2;
break;
default:
p=(caicai *)malloc(sizeof(caicai));
p->data=a[i];
p->left=p->left=NULL;
if(*BT==NULL)
*BT=p;
else
if(k==1)
s[top]->left=p;
else
s[top]->right=p;
}
i++;
}
}
int empty(caicai *BT)
{
if(BT==NULL)
return 1;
else
return 0;
}
int depth(caicai *BT)
{
int dep1,dep2;
if(BT==NULL)
return 0;
else
{
dep1=depth(BT->left);
dep2=depth(BT->right);
}
if(dep1>dep2)
return dep1;
else
return dep2;
}
char* find(caicai *BT,char x)
{
if(BT==NULL)
return NULL;
else
{
if(BT->data==x)
return &(BT->data);
else
{
char *p;
if(p=find(BT->left,x))
return p;
else if(p=find(BT->right,x))
return p;
else
return NULL;
}
}
}
void print(caicai *BT)
{
if(BT!=NULL)
{
printf("%c",BT->data);
if(BT->left!=NULL || BT->right!=NULL)
{
printf("(");
print(BT->left);
if(BT->right!=NULL)
printf(",");
print(BT->right);
printf(")");
}
}
}
void clear(caicai **BT)
{
if(*BT!=NULL)
{
clear(&((*BT)->left));
clear(&((*BT)->right));
free(*BT);
*BT=NULL;
}
}
int main()
{
caicai *bt;
char b[50],x,*px;
init(&bt);
printf("输入二叉树广义表字符串:\n");
scanf("%s",b);
creat(&bt,b);
print(bt);
printf("\n");
printf("前序:");
Preorder(bt);
printf("\n");
printf("中序:");
Inorder(bt);
printf("\n");
printf("后序:");
Postorder(bt);
printf("\n");
printf("按层:");
Levelorder(bt);
printf("\n");
printf("输入一个待查找的字符:\n");
scanf(" %c",&x);
px=find(bt,x);
if(px)
printf("查找成功:%c\n",*px);
else
printf("Fail!\n");
printf("二叉树的深度为:");
printf("%d\n",depth(bt));
clear(&bt);
return 0;
}
照着书敲的,好奇怪






