用C语言写BiTree Create(); /*按先序输入创建一棵二叉树,返回二叉树根节点指针。*/ int OperandCount(BiTree T); /*T是二叉树树根指针,函数OperandCount返回二叉树中操作数的个数,若树为空,则返回0。题目保证所给二叉树一定是正确的表达式。*/
时间: 2023-07-16 15:11:54 浏览: 61
下面是C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
/* 二叉树结构体 */
typedef struct BiTNode {
char data; // 节点数据
struct BiTNode *lchild; // 左孩子指针
struct BiTNode *rchild; // 右孩子指针
} BiTNode, *BiTree;
/* 创建二叉树 */
BiTree Create() {
BiTree T;
char ch;
scanf("%c", &ch);
if (ch == '#') { // 以 '#' 代表空节点
T = NULL;
} else {
T = (BiTree)malloc(sizeof(BiTNode));
T->data = ch;
T->lchild = Create();
T->rchild = Create();
}
return T;
}
/* 统计操作数个数 */
int OperandCount(BiTree T) {
if (T == NULL) { // 空树返回0
return 0;
}
if (T->lchild == NULL && T->rchild == NULL) { // 叶子节点返回1
return 1;
}
return OperandCount(T->lchild) + OperandCount(T->rchild); // 递归统计左右子树操作数个数之和
}
int main() {
BiTree T;
printf("按先序输入二叉树,以 '#' 代表空节点:");
T = Create();
printf("操作数个数:%d\n", OperandCount(T));
return 0;
}
```