统计所有结点数:
//统计所有结点数
int n1=0;
void countAllNode(BTNode *p)
{
if(p!=NULL)
{
++n1;
countAllNode(p->lchild);
countAllNode(p->rchild);
}
}
统计叶子结点数:
//统计叶子结点数
int n2=0;
void countLeafNode(BTNode *p)
{
if(p!=NULL)
{
if(p->lchild==NULL&&p->rchild==NULL)//判断是否叶子结点
++n2;
countLeafNode(p->lchild);
countLeafNode(p->rchild);
}
}
完整测试代码:
#include <bits/stdc++.h>
#define MaxSize 100
/*
* Created by HarvestWu on 2018/06/22.
*/
using namespace std;
typedef char ElemType;
//定义二叉树结构
typedef struct BTNode
{
ElemType data;
struct BTNode *lchild;
struct BTNode *rchild;
} BTNode;
//由先序遍历、中序遍历结果构建二叉树
BTNode *CreateBT(ElemType pre[],ElemType in[],int l1,int r1,int l2,int r2)
{
BTNode *s;
int i;
if(l1>r1)return NULL; //序列中无元素返回NULL
s=(BTNode*)malloc(sizeof(BTNode));
s->lchild=s->rchild=NULL;
for(i=l2; i<=r2; ++i)
if(in[i]==pre[l1]) //查找等于当前子树根的结点在in[]中的位置
break;
s->data=in[i];
s->lchild=CreateBT(pre,in,l1+1,l1+i-l2,l2,i-1);
s->rchild=CreateBT(pre,in,l1+i-l2+1,r1,i+1,r2);
return s; //当前子树处理完毕
}
//统计所有结点数
int n1=0;
void countAllNode(BTNode *p)
{
if(p!=NULL)
{
++n1;
countAllNode(p->lchild);
countAllNode(p->rchild);
}
}
//统计叶子结点数
int n2=0;
void countLeafNode(BTNode *p)
{
if(p!=NULL)
{
if(p->lchild==NULL&&p->rchild==NULL)
++n2;
countLeafNode(p->lchild);
countLeafNode(p->rchild);
}
}
int main()
{
BTNode *p;
ElemType pre[]= {'A','B','D','E','H','J','K','L','M','N','C','F','G','I'};
ElemType in[]={'D','B','J','H','L','K','M','N','E','A','F','C','G','I'};
//由先序遍历、中序遍历结果构建二叉树
p=CreateBT(pre,in,0,13,0,13);
cout<<"统计所有结点数:"<<endl;
countAllNode(p);
cout<<n1<<endl;
cout<<"统计叶子结点数:"<<endl;
countLeafNode(p);
cout<<n2<<endl;
return 0;
}