当前位置:编程学习 > C/C++ >>

急急急!求C语言的数据结构二叉树递归遍历程序!

求C语言的数据结构二叉树递归遍历程序!

 

补充:高手来啊!!!!!!!!
		
追问:有更好的吗?
答案:
/******************************************************/
/* 二叉树的建立深度优先遍历求叶子个数求深度 */
/******************************************************/

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#define NULL 0
typedef struct bitnode{
int data;
struct bitnode *lchild,*rchild;
}bitnode,*bitree;
/*创建一个二杈树以#号结束*/
bitree create(bitree t){
char ch;
ch=getchar();
if(ch=='#')
t=NULL;
else{
t=(bitree)malloc(sizeof(bitnode));
t->data=ch;
t->lchild=create(t->lchild);
t->rchild=create(t->rchild);
}
return t;
}
/*递归遍历*/
void preorder(bitree t){
if(t){
printf("%c",t->data); /*先序*/
preorder(t->lchild);
/*printf("%c",t->data); 中序*/
preorder(t->rchild);
/*printf("%c",t->data); 后序*/
}
}
/*求深度*/
int depth(bitree t){
int depthval,depl,depr;
if(!t)
depthval=0;
else{
depl=depth(t->lchild);
depr=depth(t->rchild);
depthval=1+(depl>depr?depl:depr);
}
return depthval;
}

/*求叶子数*/
int countleaf(bitree t){
int count=0;
if(!t)
count=0;
else if((!t->lchild)&&(!t->rchild))
count++;
else
count=countleaf(t->lchild)+countleaf(t->rchild);
return count;

}
/*主函数*/
main(){
bitree t=NULL;
printf("\nplease input a tree:");
t=create(t);
preorder(t);
printf("\ndepth:%d\nleave:%d\n",depth(t),countleaf(t));
system("pause");
}


程序以调试通过!!!!!
#include"stdio.h"//二叉树
#include"stdlib.h"
typedef struct node
{
char data;
struct node *lchild,*rchild;
}BinTNode;
typedef BinTNode* BinTree;
void GreateBinTree(BinTree *T)//以先序遍历为依据构造二叉树,T为指向根指针的指针.
{ //空结点以空格代替.
char ch;
if((ch=getchar())==' ')
*T=NULL;
else
{
*T=(BinTree)malloc(sizeof(BinTNode));
(*T)->data=ch;
GreateBinTree(&((*T)->lchild));
GreateBinTree(&((*T)->rchild));
}
}
void Lorder(BinTree T)//先序遍历二叉树.
{
if(T)
{
printf("%c ",T->data);
Lorder(T->lchild);
Lorder(T->rchild);
}
}

void Morder(BinTree T)//中序遍历二叉树.
{
if(T)
{
Morder(T->lchild);
printf("%c ",T->data);
Morder(T->rchild);
}
}
void Rorder(BinTree T)//后序遍历二叉树.
{
if(T)
{
Rorder(T->lchild);
Rorder(T->rchild);
printf("%c ",T->data);
}
}

上一个:(C语言)ASCII码前32个控制字符的含义?
下一个:用c语言编写一个可以用鼠标控制的五子棋程序

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,