📄
字号:
#include <stdio.h>
#include <math.h>
#define NULL 0
typedef int elementtype;
typedef struct node{
elementtype data;
struct node *Lchild,*Rchild;
}tree;
/* workout the tree's high */
int high(tree *t)
{
if(t==NULL) return 0;
else
return (max(high(t->Lchild),high(t->Rchild))+1);
}
/* max length of Lchild & Rchild */
int max(int x,int y)
{
if(x>y) return x;
else return y;
}
/* create a Betree */
create(tree *t,int NodeNum)
{
elementtype x;
int i,layer;
layer=log(NodeNum)/log(2)+1;
printf("\nInput data for Node %d in layer %d :",NodeNum,layer);
scanf("%d",&x);
t->data=x;
printf("create lchild for Node %d in layer %d (0 for No)?",NodeNum,layer);
scanf("%d",&i);
if(i==0) t->Lchild=NULL;
else
{
t->Lchild=(tree *)malloc(sizeof(tree));
create(t->Lchild,2*NodeNum);
}
printf("create rchild for Node %d in layer %d (0 for No)?",NodeNum,layer);
scanf("%d",&i);
if(i==0) t->Rchild=NULL;
else
{
t->Rchild=(tree *)malloc(sizeof(tree));
create(t->Rchild,2*NodeNum+1);
}
return 0;
}
/* preorder */
void preorder(tree *t)
{
if(t!=NULL)
{
printf("%d ",t->data);
preorder(t->Lchild);
preorder(t->Rchild);
}
}
/* midorder */
void midorder(tree *t)
{
if(t!=NULL)
{
midorder(t->Lchild);
printf("%d ",t->data);
midorder(t->Rchild);
}
}
/* postorder */
void postorder(tree *t)
{
if(t!=NULL)
{
postorder(t->Lchild);
postorder(t->Rchild);
printf("%d ",t->data);
}
}
/* countleaf */
int countleaf(tree *t)
{
if(t==NULL)
return 0;
if(t->Lchild==NULL&&t->Rchild==NULL)
return 1;
return(countleaf(t->Lchild)+countleaf(t->Rchild));
}
/* nodes */
int nodes(tree *t)
{
if(t==NULL)
return 0;
else
return(nodes(t->Lchild)+nodes(t->Rchild)+1);
}
void main()
{
tree *t;
t=(tree *)malloc(sizeof(tree));
create(t,1);
printf("\nThe Betree's high is:");
printf(" %d\n",high(t));
printf("\nPRESS ANY KEY TO CONTINUE will get preorder midorder postorder.");
getch();
printf("\npreorder: ");
preorder(t);
printf("\nmidorder: ");
midorder(t);
printf("\npostorder: ");
postorder(t);
getch();
printf("\nThe leaf's number is: %d",countleaf(t));
printf("\nThe total nodes' number is: %d",nodes(t));
getch();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -