请将代码修复完整#include <stdio.h> #include<malloc.h> #define MAXLEN 100 int count = 0; typedef struct tnode { char data; struct tnode* lchild, * rchild; }BT; BT *CreateBTree() { BT* t; char ch; scanf("%c", &ch); getchar(); getchar(); if (ch == '0') t = NULL; else { t = (BT*)malloc(sizeof(BT)); t->data = ch; printf("请输入%c节点的左孩子结点:", t->data); t->lchild = CreateBTree(); printf("请输入%c节点的右孩子结点:", t->data); t->rchild = CreateBTree(); } return t; } void ShowBTree(BT* T) { if (T != NULL) { printf("%c", T->data); if (T->lchild != NULL) { printf("("); ShowBTree(T->lchild); if (T->lchild != NULL) { printf(","); ShowBTree(T->rchild); } printf(")"); } else if (T->rchild != NULL) { printf("("); ShowBTree(T->lchild); if (T->rchild != NULL) { printf(","); ShowBTree(T->rchild); } printf(")"); } } } void Leafnum(BT* T) { if (T) { if (T->lchild == NULL && T->rchild == NULL) count++; Leafnum(T->lchild); Leafnum(T->rchild); } } void Leafnum(BT* T) { if (T) { count++; Leafnum(T->lchild); Leafnum(T->rchild); } } int TreeDepth(BT* T) { int ldep, rdep; if (T == NULL) return 0; else { ldep = TreeDepth(T->lchild); rdep = TreeDepth(T->rchild); if (ldep > rdep) return ldep + 1; else return rdep + 1; } }
时间: 2023-12-03 11:47:27 浏览: 94
SeqList.h #include <stdio.h> //包含标准输入输出流的头文件 #include <assert.h
以下是修复后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
int count = 0;
typedef struct tnode {
char data;
struct tnode* lchild, * rchild;
} BT;
BT* CreateBTree() {
BT* t;
char ch;
scanf("%c", &ch);
getchar();
if (ch == '0')
t = NULL;
else {
t = (BT*)malloc(sizeof(BT));
t->data = ch;
printf("请输入%c节点的左孩子结点:", t->data);
t->lchild = CreateBTree();
printf("请输入%c节点的右孩子结点:", t->data);
t->rchild = CreateBTree();
}
return t;
}
void ShowBTree(BT* T) {
if (T != NULL) {
printf("%c", T->data);
if (T->lchild != NULL) {
printf("(");
ShowBTree(T->lchild);
if (T->rchild != NULL) {
printf(",");
ShowBTree(T->rchild);
}
printf(")");
}
else if (T->rchild != NULL) {
printf("(");
ShowBTree(T->lchild);
if (T->rchild != NULL) {
printf(",");
ShowBTree(T->rchild);
}
printf(")");
}
}
}
void Leafnum(BT* T) {
if (T) {
if (T->lchild == NULL && T->rchild == NULL)
count++;
Leafnum(T->lchild);
Leafnum(T->rchild);
}
}
int TreeDepth(BT* T) {
int ldep, rdep;
if (T == NULL)
return 0;
else {
ldep = TreeDepth(T->lchild);
rdep = TreeDepth(T->rchild);
if (ldep > rdep)
return ldep + 1;
else
return rdep + 1;
}
}
int main() {
BT* root;
printf("请输入二叉树的前序遍历序列(0代表空节点):\n");
root = CreateBTree();
printf("二叉树的前序遍历序列为:\n");
ShowBTree(root);
printf("\n");
Leafnum(root);
printf("二叉树的叶子节点数为:%d\n", count);
printf("二叉树的深度为:%d\n", TreeDepth(root));
return 0;
}
```
修复的内容包括:
1. 添加了 `#include <stdlib.h>` 头文件,以使用 `malloc()` 函数。
2. 修正了 `ShowBTree()` 函数中的语法错误,`if (T->lchild != NULL)` 和 `if (T->rchild != NULL)` 应该是互斥的,因此将第二个改为 `else if (T->rchild != NULL)`。
3. 修复了 `Leafnum()` 函数的重复定义问题。
阅读全文