#include"stdlib.h"
#include"stdio.h"
typedef char DataType;
typedef struct Node
{DataType data;
struct Node *leftchild;
struct Node *rightchild;
}BiTreeNode;
void Visit(DataType item)
{printf("%c",item);
}
void
Destroy(BiTreeNode **root)
{ if((*root)!=NULL&&((*root)->leftchild!=NULL))
Destroy(&(*root)->leftchild);
if((*root)!=NULL&&((*root)->rightchild!=NULL))
Destroy(&(*root)->rightchild);
free(*root);
}
void Initiate(BiTreeNode **root)
{*root=(BiTreeNode
*)malloc(sizeof(BiTreeNode));
(*root)->leftchild=NULL;
(*root)->rightchild=NULL;
}
BiTreeNode *InsertLeftNode(BiTreeNode *curr,DataType x)
{BiTreeNode *s,*t;
if(curr==NULL)
return NULL;
t=curr->leftchild;
s=(BiTreeNode *)malloc(sizeof(BiTreeNode));
s->data=x;
s->leftchild=t;
s->rightchild=NULL;
curr->leftchild=s;
return curr->leftchild;
}
BiTreeNode *InsertRightNode(BiTreeNode *curr,DataType x)
{
BiTreeNode *s,*t;
if(curr==NULL)
return NULL;
t=curr->rightchild;
s=(BiTreeNode *)malloc(sizeof(BiTreeNode));
s->data=x;
s->rightchild=t;
s->leftchild=NULL;
curr->rightchild=s;
return curr->rightchild;
}
BiTreeNode *DeleteLeftTree(BiTreeNode *curr)
{if(curr==NULL||curr->leftchild==NULL)
return NULL;
Destroy(&curr->leftchild);
curr->leftchild=NULL;
return curr;
}
BiTreeNode *DeleteRightTree(BiTreeNode *curr)
{if(curr==NULL||curr->rightchild==NULL)
return NULL;
Destroy(&curr->rightchild);
curr->rightchild=NULL;
return curr->rightchild;
}
void PrintBiTree(BiTreeNode *bt,int n)
{int i;
if(bt==NULL)return;
PrintBiTree(bt->rightchild,n+1);
for(i=0;i<n;i++)printf("
");
if(n>=0)
{printf("------");
printf("%c\n",bt->data);
}
PrintBiTree(bt->leftchild,n+1);
}
void PreOrder(BiTreeNode *t,void Visit(DataType item))
{if(t!=NULL)
{Visit(t->data);
PreOrder(t->leftchild,Visit);
PreOrder(t->rightchild,Visit);
}
}
void PostOrder(BiTreeNode *t,void Visit(DataType item))
{if(t!=NULL)
{ PostOrder(t->leftchild,Visit);
PostOrder(t->rightchild,Visit);
Visit(t->data);
}
}
int leafsum(BiTreeNode *s)/*统计叶子结点数并打印叶子节点*/
{ int n;
if(s==NULL) return 0;
if(s->leftchild==NULL&&s->rightchild==NULL)
{Visit(s->data);
leafsum(s->leftchild);
leafsum(s->rightchild);
printf("\n");
return 1;}
n=(leafsum(s->leftchild)+leafsum(s->rightchild));
return n;
}
void
main(void)
{int t;
BiTreeNode *root,*p,*pp;
Initiate(&root);
p=InsertLeftNode(root,'A');
p=InsertLeftNode(p,'B');
p=InsertLeftNode(p,'D');
p=InsertRightNode(p,'G');
p=InsertRightNode(root->leftchild,'C');
pp=p;
InsertLeftNode(p,'E');
InsertRightNode(pp,'F');
PrintBiTree(root,0);
printf("前序遍历:");
PreOrder(root->leftchild,Visit);
printf("\n后序遍历:");
PostOrder(root->leftchild,Visit);
printf("\n");
t=leafsum(root->leftchild);/*这个是求得叶子结点*/
printf("%d",t);
Destroy(&root);
}
欢迎参考哦!!这是我自己做的,是可以实现的!大家学习一下吧