|
|
#2
hzh5122010-06-03 20:25
|
计算任一一层的叶子结点数
我的代码:
#include <stdio.h>
#include <malloc.h>
#define maxsize 100
typedef char ElemType;
typedef struct node
{
ElemType data;
struct node *lchild,*rchild;
}BiNode,*BiTree;
BiTree CreatBiTree()
{
BiTree T;
ElemType x;
scanf("%c",&x);
if(x=='#') T=NULL;
else
{
T=(BiTree)malloc(sizeof(BiNode));
T->data=x;
T->lchild=CreatBiTree();
T->rchild=CreatBiTree();
}
return T;
}
int Leaves(BiTree T,int k)
{
BiTree tree[maxsize];
int i,front,rear,last,level,leaf;
tree[1]=T;
front=1;
rear=2;
level=1;
last=2;
leaf=0;
while(level<k)
{
if(tree[front]->lchild) tree[rear++]=tree[front]->lchild;
if(tree[front]->rchild) tree[rear++]=tree[front]->rchild;
front++;
if(front==last) { level++;last=rear; }
}
for(i=front;i<rear;i++)
if(!tree[i]->lchild&&!tree[i]->rchild) leaf++;
return leaf;
}
int main()
{
BiTree T;
int k,x;
T=CreatBiTree();
scanf("%d",&k);
x=Leaves(T,k);
printf("%d",x);
return 0;
}
编译过了,可是运行时显示栈错误 *_*
程序代码: