统计二叉树的结点个数

2024-12-14 00:01:19
推荐回答(4个)
回答1:

void getNum(Node*p,int &n)
{
if(p!=NULL)
{
n=n+1;
getNum(p->Left,n);
getNum(p->Right,n);
}
else
{
return ;
}

}

其中 p为二叉树指针 , n返回的是 节点个数, n传参前需初始化为0;

回答2:

#include
#include
typedef struct node
{ char data;
struct node *lchild,*rchild;
}JD;
void countleaf(JD *bt,int *count)
{ if(bt!=NULL)
{ if((bt->lchild==NULL)&&(bt->rchild==NULL))
{ (*count)++;
return;
}
countleaf(bt->lchild,count);
countleaf(bt->rchild,count);
}
}
JD *crt_bt_pre(JD *bt)
{ char ch;
printf("ch=");
scanf("%c",&ch);
getchar();
if(ch==' ') bt=NULL;
else
{ bt=(JD *)malloc(sizeof(JD));
bt->data=ch;
bt->lchild=crt_bt_pre(bt->lchild);
bt->rchild=crt_bt_pre(bt->rchild);
}
return(bt);
}
void main()
{ /* ABC00DE0G00F000 */
JD *head=NULL;
int count=0;
head=crt_bt_pre(head);
countleaf(head,&count);
printf("count of leaf node is %d\n",count);
}

回答3:

回答4:

void size(BONode *T)

if(T!=NULL)
return 1+size(T-lchild)+size(T-rchild);
else
return 0;