#include<stdio.h>
#include<stdlib.h>
typedef struct bt
{char data;
struct bt *lchild;
struct bt *rchild;
}bt;
bt *createTree()
{bt *t;
char x;
scanf("%c",&x);
getchar();
if(x=='0')t=NULL;
else{
t=(bt *)malloc(sizeof(bt));
t->data=x;
printf("\n请输入%c结点的左结点:",t->data);
t->lchild=createTree();
printf("\n请输入%c结点的右结点:",t->data);
t->rchild=createTree();
}
return t;
}
void display(bt *t,int i)//凹入显示
{int j;
if(t==NULL)return;
else{
for(j=0;j<i;j++)printf(" ");
printf("%c",t->data);
for(j=i+1;j<30;j++)
printf("-");
printf("\n");
i=i+2;
display(t->lchild,i);
display(t->rchild,i);
i=i-2;
}
}
//遍历先序
void preorder(bt *t)
{if(t==NULL)return;
else{
printf("%3c",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
//中序遍历
void inorder(bt *t)
{if(t==NULL)return;
else{
inorder(t->lchild);
printf("%3c",t->data);
inorder(t->rchild);
}
}
//后序遍历
void postorder(bt *t)
{if(t==NULL)return;
else{
postorder(t->lchild);
postorder(t->rchild);
printf("%3c",t->data);
}
}
//层次遍历
void levelorder(bt *t)
{int i,j;
bt *q[40],*p;
p=t;
if(p!=NULL){i=1;q[i]=p;j=2;}
while(i!=j)
{p=q[i];printf("%3c",p->data);
if(p->lchild!=NULL){q[j]=p->lchild;j++;}
if(p->rchild!=NULL){q[j]=p->rchild;j++;}
i++;
}}
int node(bt *t)
{int num1=0,num2=0;
if(!t) return 0;
if(t->lchild==NULL&&t->rchild==NULL)
return 1;
else{
num1=node(t->lchild);
num2=node(t->rchild);
}
return num1+num2+1;
}
int count=0;
void lefnum(bt *t)
{if(t==NULL)return;
if(t->lchild==NULL&&t->rchild==NULL)count++;
else{
lefnum(t->lchild);
lefnum(t->rchild);}
}
int TreeDepth(bt *t)
{int ldep,rdep;
if(t==NULL)return 0;
else{
ldep=TreeDepth(t->lchild);
rdep=TreeDepth(t->rchild);
if(ldep>rdep)return ldep+1;
else return rdep+1;
}
}
int main()
{
bt *root=NULL;
printf("\n请按先序输入二叉树的结点,若无结点请输入0:");
printf("请输入根结点:\n");
root=createTree();
printf("二叉树创建成功!\n");
printf("二叉树凹入表示法如下:\n");
display(root,4);
printf("二叉树的先序遍历为:");
preorder(root);
printf("二叉树的中序遍历为:");
inorder(root);
printf("二叉树的后序遍历为:");
postorder(root);
printf("二叉树的层次遍历为:");
levelorder(root);
printf("二叉树的结点数为:");
lefnum(root);
printf("二叉树的叶子数为:%d",count);
printf("二叉树的深度为:%d",TreeDepth(root));
return 0;
}
叉树的遍历、结点计算
最新推荐文章于 2024-07-18 14:40:48 发布