|
发表于 2014-4-17 12:22:14
|
显示全部楼层
简单的二叉树,刚学,只有建立 和遍历,谅解,,
#include<stdio.h>
#include<stdlib.h>
#define MAX 50
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}BTnode;
BTnode *Create(char *str);
void Show(BTnode *p);
void Pre(BTnode *p);
void Mid(BTnode *p);
void Pos(BTnode *p);
int main()
{
char *str =NULL;
BTnode *p=NULL;
int choice ;
str =(char *)malloc(MAX);///why ? what is means
printf("输入一个二叉树(括号嵌套法表示) \n");
gets(str);
p=Create(str);
printf( "----------\n");
printf("输出生成的二叉树 \n");
//Show(p);
printf("\n");
while(1)
{
printf("二叉树遍历练习\n");
printf("1.先序遍历\n");
printf("2.中序遍历\n");
printf("3.后序遍历\n");
printf("4.退出程序 \n");
printf("请选择功能\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
Pre(p);
printf("\n");
break;
case 2:
Mid(p);
printf("\n");
break;
case 3:
Pos(p);
printf("\n");
break;
case 4:
return 1;
break;
}
}
return 0;
}
// cerate ()
BTnode *Create(char *str)
{
BTnode *s[MAX],*p,*p1,*B=NULL;
int i=0,top= -1,flag;
char ch;
ch =str[0];
while(ch!='\0')
{
switch (ch)
{
case '(':
top++;
//s[top]=p;
flag=1;
printf("--1---\n");
break;
case ')':
top--;
printf("--2---\n");
break;
case ',':
printf("--3---\n");
flag=2;
break;
default:
printf("--4---\n");
p=(BTnode*)malloc(sizeof(BTnode));
p->data=ch;
p->lchild=NULL;
p->rchild=NULL;
if(B==NULL)
{
B=p;
p1=B;
s[top]=p1;
}
else
if(flag==1)
{ p1=s[top-1];
//printf("00000000000000\n");
s[top]=p;
p1->lchild=p;
//p1=p;
}
//p1=p;
else
if(flag==2)
{
p1=s[top-1];
s[top]=p;
//s[top]->rchild=p;
p1->rchild=p;
//p1=p;
}
break;
}
i++;
ch=str[i];
}
return B;
}
/*shu chu
void Show(BTnode *p)
{
if(p!=NULL)
{
printf("%c",p->data);
if(p->rchild!=NULL||p->rchild!=NULL)
{
printf("(");
Show(p->lchild);
if(p->rchild!=NULL)
{
printf(",");
Show(p->rchild);
}
printf(")");
}
}
}
void Show2(BTnode *p)
{
}
//pre
void Pre(BTnode *p)
{
if(p!=NULL)
{
putchar(p->data);
Pre(p->lchild);
Pre(p->rchild);
}
}
//Mid
void Mid(BTnode *p)
{
i++
if(p!=NULL)
{
Mid(p->lchild);
putchar(p->data);
Mid(p->rchild);
}
}
*/
//pos
void Pos(BTnode *p)
{
if(p!=NULL)
{
Pos(p->lchild);
Pos(p->rchild);
putchar(p->data);
}
} |
|