按先序次序建立以下二叉树,然后按先序的顺序输出结点的值、层次、左右孩子结点;用C语言编写,初学数据结

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/04 08:33:58
按先序次序建立以下二叉树,然后按先序的顺序输出结点的值、层次、左右孩子结点;用C语言编写,初学数据结

按先序次序建立以下二叉树,然后按先序的顺序输出结点的值、层次、左右孩子结点;用C语言编写,初学数据结
按先序次序建立以下二叉树,然后按先序的顺序输出结点的值、层次、左右孩子结点;用C语言编写,初学数据结

按先序次序建立以下二叉树,然后按先序的顺序输出结点的值、层次、左右孩子结点;用C语言编写,初学数据结
#include
#include
#include
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef char elemtype;
typedef struct BiTNode{
elemtype data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//构造二叉树
Status CreateBiTree(BiTree &T){
elemtype ch;
ch=getchar();
if(ch==' '){T=NULL;}
else{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
return FALSE;
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
return OK;

}
// 先序遍历
void PreOrderTraverse(BiTree T){
if(T!=NULL){
printf("%c ",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
//叶子节点的个数
Status Leafnumber(BiTree T){
int num1=0,num2=0;
if(T==NULL)
return 0;
else if (T->lchild==NULL&&T->rchild==NULL) return 1;
else
{
num1=Leafnumber(T->lchild);
num2=Leafnumber(T->rchild);
return(num1+num2);
}
}
//树的深度
Status DepthTree(BiTree T){
int llength=0,rlength=0;
if(T==NULL) return 0;
else{
llength=DepthTree(T->lchild);
rlength=DepthTree(T->rchild);
return(llength>rlength)?(llength+1):(rlength+1);
}
}
void main()
{
BiTree s;
printf("输入字符串,使用空格代表空\n");
CreateBiTree(s);
printf("先序输出:\n");
PreOrderTraverse(s);
printf("\n树的深度:%d\n",DepthTree(s));
getch();
}