用c语言编写一个程序 btree.c , 实现二叉树的基本运算,并在此基础上设计exp7-1.c,完成如下功能: (1)由如图7. 1所示的二叉树创建对应的二叉链存 储结构6, 该二叉树的括号表示 串为"A(B(D,E(H(J,K (L,M(,N))))),C(F,G(,I)))" (2)输出二叉树b。 (3)输出'H'结点的左、右孩子结点值。 (4)输出二叉树b的高度 。 (5)释放二叉树 b 。
时间: 2023-10-30 07:04:41 浏览: 136
btree.c 代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BTNode {
ElemType data;
struct BTNode *left, *right;
} BTNode, *BTree;
BTree createBTree(char *s, int *i) {
BTree t = NULL;
if (s[*i] != '(') {
return NULL;
}
(*i)++;
if (s[*i] != ')') {
t = malloc(sizeof(BTNode));
t->data = s[*i];
t->left = createBTree(s, i);
t->right = createBTree(s, i);
}
(*i)++;
return t;
}
void printBTree(BTree t) {
if (t == NULL) {
printf("()");
return;
}
printf("(%c", t->data);
if (t->left || t->right) {
printBTree(t->left);
printBTree(t->right);
}
printf(")");
}
void printNode(BTree t, ElemType x) {
if (t == NULL) {
return;
}
if (t->data == x) {
if (t->left) {
printf("左孩子:%c\n", t->left->data);
}
if (t->right) {
printf("右孩子:%c\n", t->right->data);
}
return;
}
printNode(t->left, x);
printNode(t->right, x);
}
int getHeight(BTree t) {
if (t == NULL) {
return 0;
}
int leftHeight = getHeight(t->left);
int rightHeight = getHeight(t->right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
void freeBTree(BTree t) {
if (t == NULL) {
return;
}
freeBTree(t->left);
freeBTree(t->right);
free(t);
}
```
exp7-1.c 代码如下:
```c
#include <stdio.h>
#include "btree.c"
int main() {
char s[] = "A(B(D,E(H(J,K(L,M,N)))),C(F,G(,I)))";
int i = 0;
BTree b = createBTree(s, &i);
printf("二叉树 b:");
printBTree(b);
printf("\n'H'结点的左、右孩子结点值:\n");
printNode(b, 'H');
printf("二叉树 b 的高度:%d\n", getHeight(b));
freeBTree(b);
return 0;
}
```
注意:需要将 btree.c 和 exp7-1.c 放在同一目录下编译链接。
阅读全文