改正void Count(BiTree T) {//二叉树结点个数的统计 /**************begin************/ int sum=Ncount(T); if (T == NULL); else { if (T->lchild == NULL && T->rchild == NULL) a++; Count(T->lchild, a, b, c); Count(T->rchild, a, b, c); } c = a - 1; b = sum - c - a; /**************end************/ }
时间: 2023-06-16 21:03:58 浏览: 50
void Count(BiTree T, int &a, int &b, int &c) {//二叉树结点个数的统计
if (T == NULL) return;
if (T->lchild == NULL && T->rchild == NULL) a++;
Count(T->lchild, a, b, c);
Count(T->rchild, a, b, c);
c = a - 1;
int sum = a + b + c;
b = sum - c - a;
}
修改后的代码中,我增加了三个参数 a、b、c 用来统计二叉树中叶子结点个数、只有左子树或右子树的结点个数以及有左右子树的结点个数。同时我使用了引用传递,以便在函数内部对 a、b、c 进行修改。另外,我还修改了 if 语句后面的分号,以免分号将 if 语句的作用域限制在了 if 语句本身而忽略了后面的代码。最后,我还添加了一行代码重新计算二叉树的结点总数 sum。
相关问题
设计算法按先序次序打印统计二叉树T中叶子 结点的个数(用全局变量的方法)。 void NodeCount(BiTree *T)
以下是按先序次序打印统计二叉树T中叶子结点个数的算法:
```
int count = 0; // 全局变量,记录叶子节点个数
void NodeCount(BiTree *T) {
if(T == NULL) {
return;
}
if(T->lchild == NULL && T->rchild == NULL) { // 如果当前节点是叶子节点
count++;
}
NodeCount(T->lchild); // 递归遍历左子树
NodeCount(T->rchild); // 递归遍历右子树
}
```
在主函数中调用该算法即可统计出二叉树中叶子节点的个数:
```
int main() {
BiTree *T; // 假设已经创建了一棵二叉树
NodeCount(T);
printf("叶子节点个数为:%d", count);
return 0;
}
```
#include<iostream> #include<string.h> using namespace std; int a,b,c;//a、b、c分别表示度为0、1、2的结点个数 typedef struct BiTNode { char data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; void CreateBiTree(BiTree &T,char S[],int &i) {//先序建立二叉树 if(S[i]=='0') T=NULL; else { T=new BiTNode; T->data=S[i]; CreateBiTree(T->lchild,S,++i); CreateBiTree(T->rchild,S,++i); } } void Count(BiTree T) {//二叉树结点个数的统计 /**************begin************/ /**************end************/ } int main() { char S[100]; while(cin>>S) { if(strcmp(S,"0")==0) break; a=b=c=0; int i=-1; BiTree T; CreateBiTree(T,S,++i); Count(T); cout<<a<<" "<<b<<" "<<c<<endl; } return 0; }
好的,我理解您需要的是完整的程序代码。以下是完整程序代码:
```c++
#include<iostream>
#include<string.h>
using namespace std;
int a, b, c; // a、b、c 分别表示度为0、1、2的结点个数
typedef struct BiTNode {
char data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
void CreateBiTree(BiTree &T, char S[], int &i) { // 先序建立二叉树
if (S[i] == '0') {
T = NULL; // 如果当前字符为 0,则结点为空
} else {
T = new BiTNode; // 创建新结点
T->data = S[i]; // 将当前字符赋值给结点数据域
CreateBiTree(T->lchild, S, ++i); // 递归建立左子树
CreateBiTree(T->rchild, S, ++i); // 递归建立右子树
}
}
void Count(BiTree T) { // 二叉树结点个数的统计
if (T == NULL) { // 如果当前结点为空,则返回
return;
}
if (T->lchild == NULL && T->rchild == NULL) { // 如果左右孩子都为空,说明是度为0的结点
a++;
} else if (T->lchild != NULL && T->rchild != NULL) { // 如果左右孩子都不为空,说明是度为2的结点
c++;
} else { // 否则,说明是度为1的结点
b++;
if (T->lchild != NULL) {
Count(T->lchild);
} else {
Count(T->rchild);
}
}
}
int main() {
char S[100];
while (cin >> S) {
if (strcmp(S, "0") == 0) break;
a = b = c = 0;
int i = -1;
BiTree T;
CreateBiTree(T, S, ++i);
Count(T);
cout << a << " " << b << " " << c << endl;
}
return 0;
}
```
这个程序可以读入多个由先序遍历序列表示的二叉树,并分别统计它们的度为0、1、2的结点个数,并输出结果。每个二叉树的先序遍历序列以 0 结尾,程序会自动终止读入并退出。