#include<stdio.h>
#include<stdlib.h>
#include <stack>
#include <queue>
using namespace std;
//层次建树
typedef struct TreeNode {
char data;
struct TreeNode* Lchild;//左结点
struct TreeNode* Rchild;//右结点
}TreeNode, * Tree;
typedef struct TreeQueue {
Tree T;
struct TreeQueue* next;
}TreeQueue, * TrQueue;//辅助队列
int Leafcount(Tree& T) {
if (!T) {
return 0;
}
else if (T->Lchild==NULL&&T->Rchild==NULL)
return 1;
else
return Leafcount(T->Lchild)+Leafcount(T->Rchild);
}
int main()
{
Tree Tr = NULL;
TrQueue phead = NULL, ptail = NULL, pcur = NULL;//为了下次还能找到整个队列,使用pcur来代替phead模拟出队操作
TrQueue newQ;//创建新树结点
Tree newT;//创建新队列结点
char c;
while (scanf("%c", &c) != EOF) {
if (c == '\n')
break;
newT = (Tree)calloc(1, sizeof(TreeNode));//calloc可以进行初始化,赋值为NULL
newT->data = c;//创建完成一个树的节点
newQ = (TrQueue)calloc(1, sizeof(TreeQueue));//最好定义在外部,不然后在下一个{}中就失效了
newQ->T = newT;//创建完成一个保存树节点指针的队列结点
if (Tr == NULL)//此时如果树还没有根结点
{
Tr = newT;
phead = newQ;
ptail = newQ;
pcur = newQ;
}
else {
ptail->next = newQ;
ptail = ptail->next;//先尾插法加入队列尾部
if (pcur->T->Lchild == NULL) {//先检查队头树结点的左子树是否为空,为空加入新结点
pcur->T->Lchild = newT;
}
else if (pcur->T->Rchild == NULL)//若左子树不为空,再检查队头树结点的左子树是否为空,为空加入新结点
{
pcur->T->Rchild = newT;
pcur = pcur->next;//队头树结点已满,进行出队操作
}
//else {//若两边都不为空-----你写对的话,应该不存在这种情况了
//}
}
}
printf("总叶子结点数:%d",Leafcount(Tr));
}
// ABCDEFG
辅助队列层序建树+统计叶子结点数(二叉树)
最新推荐文章于 2024-06-18 13:52:22 发布