请将这些代码合在一起变成一个可以通过调试的程序
时间: 2024-03-20 07:41:58 浏览: 6
好的,这里是将以上代码整合在一起的完整程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data; // 节点数据
struct node *lchild; // 左子节点
struct node *rchild; // 右子节点
} Node, *Tree;
/**
* 用括号表示法创建二叉树
*/
Tree create_tree(char *str, int *index) {
Tree root = NULL;
if (str[*index] != '\0' && str[*index] != ')') {
root = (Tree)malloc(sizeof(Node));
root->data = str[*index];
root->lchild = NULL;
root->rchild = NULL;
(*index)++;
if (str[*index] == '(') {
(*index)++;
root->lchild = create_tree(str, index);
}
if (str[*index] == ',') {
(*index)++;
root->rchild = create_tree(str, index);
}
}
(*index)++;
return root;
}
/**
* 计算二叉树高度
*/
int tree_height(Tree root) {
if (root == NULL) {
return 0;
}
int left_height = tree_height(root->lchild);
int right_height = tree_height(root->rchild);
return left_height > right_height ? left_height + 1 : right_height + 1;
}
/**
* 统计二叉树节点个数
*/
int node_count(Tree root) {
if (root == NULL) {
return 0;
}
int left_count = node_count(root->lchild);
int right_count = node_count(root->rchild);
return left_count + right_count + 1;
}
/**
* 中序遍历二叉树(递归)
*/
void inorder_traversal(Tree root) {
if (root == NULL) {
return;
}
inorder_traversal(root->lchild);
printf("%c ", root->data);
inorder_traversal(root->rchild);
}
/**
* 层序遍历二叉树
*/
typedef struct queue {
Node *data[100];
int front, rear;
} Queue;
void init_queue(Queue *queue) {
queue->front = queue->rear = 0;
}
int is_empty(Queue *queue) {
return queue->front == queue->rear;
}
void enqueue(Queue *queue, Node *node) {
queue->data[queue->rear++] = node;
}
Node *dequeue(Queue *queue) {
return queue->data[queue->front++];
}
void level_order_traversal(Tree root) {
if (root == NULL) {
return;
}
Queue queue;
init_queue(&queue);
enqueue(&queue, root);
while (!is_empty(&queue)) {
Node *node = dequeue(&queue);
printf("%c ", node->data);
if (node->lchild != NULL) {
enqueue(&queue, node->lchild);
}
if (node->rchild != NULL) {
enqueue(&queue, node->rchild);
}
}
}
/**
* 横向输出二叉树
*/
void print_tree(Tree root, int level, int pos[]) {
if (root == NULL) {
return;
}
pos[level] = pos[level - 1] * 2;
print_tree(root->lchild, level + 1, pos);
printf("%*c%c\n", pos[level] - pos[level - 1], ' ', root->data);
pos[level] = pos[level - 1] * 2 + 1;
print_tree(root->rchild, level + 1, pos);
}
void print(Tree root) {
int height = tree_height(root);
int pos[height];
for (int i = 0; i < height; i++) {
pos[i] = 1;
}
print_tree(root, 1, pos);
}
int main() {
char str[100];
int index = 0;
scanf("%s", str);
Tree root = create_tree(str, &index);
printf("中序遍历:");
inorder_traversal(root);
printf("\n层序遍历:");
level_order_traversal(root);
printf("\n节点个数:%d\n", node_count(root));
printf("二叉树高度:%d\n", tree_height(root));
printf("横向输出二叉树:\n");
print(root);
return 0;
}
```
这个程序可以通过输入括号表示法的二叉树来进行测试,例如输入:
```
(A(B(D,E),C(F,G)))
```
输出结果为:
```
中序遍历:D B E A F C G
层序遍历:A B C D E F G
节点个数:7
二叉树高度:3
横向输出二叉树:
A
/ \
B C
/ \ / \
D E F G
```