保温瓶玻璃内胆:建立二叉树的先序遍历(用递归的方法)c语言源代码

来源:百度文库 编辑:中科新闻网 时间:2024/04/29 23:28:32
要求能够输入树的各个结点,并能够输出不同方法遍历的遍历序列;分别建立二叉树存储结构的输入函数,输出先序遍历序列的函数。
(希望各位高手能写出源程序和注释)

#include<iostream.h>
#include<stdio.h>
struct tree
{
char d;
struct tree *lc,*rc;
};
struct tree* create()
{
struct tree*p;
char c;
cout<<"请输入结点:";
fflush(stdin);
cin>>c;
if(c=='#') return 0;
p=new struct tree;
p->d=c;
p->lc=create();
p->rc=create();
return p;
}
void first(struct tree*q)
{
if(!q) return;
cout<<q->d<<",";
first(q->lc);
first(q->rc);
}
void last(struct tree*q)
{
if(!q) return;
last(q->lc);
last(q->rc);
cout<<q->d<<",";
}
void mid(struct tree*q)
{
if(!q) return;
mid(q->lc);
cout<<q->d<<",";
mid(q->rc);
}
int heigh(struct tree*q)
{
int lh,rh;
if(q==0) return 0;
lh=heigh(q->lc);
rh=heigh(q->rc);
return (lh>rh?lh:rh)+1;
}
void main()
{
struct tree*head;
head=create();
cout<<"树的高为:"<<heigh(head)<<endl;
cout<<"前序排列为:";
first(head);
cout<<endl;
cout<<"中序排列为:";
mid(head);
cout<<endl;
cout<<"后序排列为:";
last(head);
cout<<endl;
}

如果子为空记的输入‘#’代表空呀
哈哈

void xianxu(TREE* t)
{
if(t != NULL)
{
printf("当前接点",...);
xianxu(t->lchild);
xianxu(t->rchild);
}
}

#define LEN sizeof(struct tree)
#define NULL 0
#include<malloc.h>
struct tree
{
char data;
struct tree*lchild,*rchild;
};

struct tree*creat()
{
char c;
struct tree*t;
scanf("%c",&c);
if(c=='#') t=NULL;
else
{
t=(struct tree*)malloc(LEN);
t->data=c;
t->lchild= creat( );
t->rchild= creat( );
}
return t;
}

void print (struct tree*t)
{if(t!=NULL)
{
print(t->lchild);
print(t->rchild);
printf("%c",t->data) ;
}
}

main()
{ struct tree*t ;
t=creat();
print(t);
}