树和二叉树的建立及应用

来源:百度知道 编辑:UC知道 时间:2024/06/08 06:26:06
二叉树采用二叉链表作存储结构,试编程实现二叉树的如下基本操作:
1.按先序序列构造一棵二叉链表表示的二叉树T;
2.对这棵二叉树进行遍历:先序、层次遍历序列,分别输出结点的遍历序列;
3.求二叉树的深度/叶结点数目;
要求用C语言实现。

以下是我的数据结构实验的作业:肯定好用,里面还包括了统计树的深度和叶子数!记住每次做完一个遍历还要重新输入你的树哦!
#include "stdio.h"
#include "string.h"
#define NULL 0
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree Create(BiTree T){
char ch;
ch=getchar();
if(ch=='#')
T=NULL;
else{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
printf("Error!");
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);
Preorder(T->rchild);
}
}
int Sumleaf(BiTree T){
int sum=0,m,n;
if(T){
if((!T->lchild)&&(!T->rchild))
sum++;
m=Sumleaf(T->lchild);
sum+=m;
n=Sumleaf(T->rchild);
sum+=n;
}
return sum;