#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef char *BTree;
typedef enum{OVERFLOW=-2,ERROR,FALSE,OK,TRUE} Status;
Status InitBTree(BTree *bt,char *Node)
{
int Length;
int i;
for(Length=0;Node[Length];Length++); /*确定二叉树的节点数*/
*bt=(BTree)malloc((Length+1)*sizeof(char));/*分配存储空间,0#单元保存长度*/
if(!(*bt)) exit(OVERFLOW);
(*bt)[0]=Length;
for(i=0;i<Length;i++)
(*bt)[i+1]=Node[i];
return OK;
}
Status Visit(char c)
{
printf("%c",c);
return OK;
}
Status PreorderTraverse(BTree bt,int i)
{ /*递归先序遍历*/
if(i<=bt[0] && bt[i]!='#')
{
Visit(bt[i]);
if(2*i<=bt[0] && bt[2*i]!='#') PreorderTraverse(bt,2*i);
if(2*i+1<=bt[0] && bt[2*i+1]!='#') PreorderTraverse(bt,2*i+1);
}
return OK;
}
void Leaf(BTree bt,int *count)
{ /*计算二叉树的叶子数*/
if (bt) {
Leaf(bt->lchild,count);
/* 计算左子树的叶子结点个数 */
if (bt->lchild==NULL && bt->rchild==NULL) (*count)++;
Leaf(bt->rchild,count);
/* 计算右子树的叶子结点个数 */
}
}
void main()
{
char *node="ABCDEFG##H#IJ#K"; /*二叉树初始串*/
BTree *bt;
int count=0;
InitBTree(&bt,node); /*用初始串构造一个顺序存储的二叉树*/
printf("先序遍历:\n\t");
PreorderTraverse(bt,1);
printf("\n");
Leaf(bt,&count);
printf("\nThe number of leaves is %d\n",count);
getch();
}
我的编辑环境是win-TC ,但愿能对你有帮助。
温馨提示:答案为网友推荐,仅供参考