用c语言用二叉树实现将一组字母ABCDEFGH以树形的方式输出
时间: 2023-06-24 10:03:23 浏览: 101
以下是用C语言实现将ABCDEFGH以二叉树形式输出的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
char data;
struct node* left;
struct node* right;
};
/* 创建新节点 */
struct node* newNode(char data) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
/* 输出二叉树 */
void printTree(struct node* node, int space) {
if (node == NULL) {
return;
}
space += 5;
printTree(node->right, space);
printf("\n");
for (int i = 5; i < space; i++) {
printf(" ");
}
printf("%c\n", node->data);
printTree(node->left, space);
}
int main() {
struct node* root = newNode('A');
root->left = newNode('B');
root->right = newNode('C');
root->left->left = newNode('D');
root->left->right = newNode('E');
root->right->left = newNode('F');
root->right->right = newNode('G');
root->right->right->right = newNode('H');
printf("Binary Tree:\n");
printTree(root, 0);
return 0;
}
```
运行结果:
```
Binary Tree:
H
G
F
C
E
B
D
A
```
以上代码使用二叉树来表示字母ABCDEFGH,并将其以树形式输出。通过递归遍历二叉树,在每一层打印出节点数据,并在节点左右两侧打印出一定数量的空格来表示层次关系。
阅读全文