#include<stdio.h>/*2009.10.10晚 写于白鹿原*/ #include<malloc.h>/*输出二叉树叶子节点、叶子节点数目、二叉树高度*/ #include<conio.h> typedef int DataType; int count=0;//用于统计叶子节点的数目// typedef struct Node { DataType data; struct Node *LChild; struct Node *RChild; }BitNode,*BitTree; void CreatBiTree(BitTree *bt)//用扩展先序遍历序列创建二叉树,如果是.当前树根置为空,否则申请一个新节点// { char ch; ch=getchar(); if(ch=='.')*bt=NULL; else { *bt=(BitTree)malloc(sizeof(BitNode)); (*bt)->data=ch; CreatBiTree(&((*bt)->LChild)); CreatBiTree(&((*bt)->RChild)); } } void PreOrder(BitTree root)//先序遍历输出二叉树的叶子节点// { if(root!=NULL) { if(root->LChild==NULL&&root->RChild==NULL) printf("%c ",root->data); PreOrder(root->LChild); PreOrder(root->RChild); } } void LeafCount(BitTree root)//后续遍历计数统计叶子节点的数目 { if(root!=NULL) { LeafCount(root->LChild); LeafCount(root->RChild); if(root->LChild==NULL&&root->RChild==NULL) count++; } } int leaf(BitTree root)//后续遍历递归返值统计叶子节点数目// { int LeafCount; if(root==NULL) LeafCount=0; else if((root->LChild==NULL)&&(root->RChild==NULL)) LeafCount=1; else LeafCount=leaf(root->LChild)+leaf(root->RChild); return LeafCount; } int PostTreeDepth(BitTree bt)//后续遍历求二叉树高度递归算法// { int hl,hr,max; if(bt!=NULL) { hl=PostTreeDepth(bt->LChild); hr=PostTreeDepth(bt->RChild); max=hl>hr?hl:hr; return(max+1); } else return 0; } void main() { BitTree T; int num; printf("请输入二叉树中的元素(以扩展先序遍历序列输入,其中.代表空子树):/n"); CreatBiTree(&T); printf("该二叉树的叶子节点为:/n"); PreOrder(T); printf("/n该二叉树的叶子节点数目为(第一种方法):/n"); LeafCount(T); printf("%d ",count); printf("/n该二叉树的叶子节点数目为(第二种方法):/n"); num=leaf(T); printf("%d ",num); printf("/n该二叉树的高度为:/n"); num=PostTreeDepth(T); printf("%d ",num); getch(); }