直接看代码
#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct BTree{
ElemType data;
struct BTree *lchild,*rchild;
}BTree;
BTree *CreateTree()
{
char ch;
BTree *bt;
bt = NULL;
ch = getchar();
if(ch!='#'){
bt = (BTree*)malloc(sizeof(BTree));
bt->data = ch;
bt->lchild = CreateTree();
bt->rchild = CreateTree();
}
return bt;
}
int CountDegree(BTree *bt)
{
if(!bt)
return 0;
if((bt->lchild&&!bt->rchild)||(!bt->lchild&&bt->rchild))
return 1 + CountDegree(bt->lchild) + CountDegree(bt->rchild);
else
return 0 + CountDegree(bt->lchild) + CountDegree(bt->rchild);
}
void CountDegree_2(BTree *bt,int *n)
{
if(bt){
CountDegree_2(bt->lchild,n);
if((bt->lchild&&!bt->rchild)||(!bt->lchild&&bt->rchild))
*n = *n + 1;
CountDegree_2(bt->rchild,n);
}
}
int main()
{
BTree *bt;
int n = 0;
bt = CreateTree();
CountDegree_2(bt,&n);
printf("%d\n",CountDegree(bt));
printf("%d\n",n);
return 0;
}