C语言创建以A,B,C,D,E,F,G,H,I,J为节点的二叉树
时间: 2023-10-03 11:04:15 浏览: 92
用C语言实现的二叉树
下面是用C语言创建以A,B,C,D,E,F,G,H,I,J为节点的二叉树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树
TreeNode* createTree() {
// 创建节点A
TreeNode *A = (TreeNode*)malloc(sizeof(TreeNode));
A->val = 'A';
// 创建节点B
TreeNode *B = (TreeNode*)malloc(sizeof(TreeNode));
B->val = 'B';
// 创建节点C
TreeNode *C = (TreeNode*)malloc(sizeof(TreeNode));
C->val = 'C';
// 创建节点D
TreeNode *D = (TreeNode*)malloc(sizeof(TreeNode));
D->val = 'D';
// 创建节点E
TreeNode *E = (TreeNode*)malloc(sizeof(TreeNode));
E->val = 'E';
// 创建节点F
TreeNode *F = (TreeNode*)malloc(sizeof(TreeNode));
F->val = 'F';
// 创建节点G
TreeNode *G = (TreeNode*)malloc(sizeof(TreeNode));
G->val = 'G';
// 创建节点H
TreeNode *H = (TreeNode*)malloc(sizeof(TreeNode));
H->val = 'H';
// 创建节点I
TreeNode *I = (TreeNode*)malloc(sizeof(TreeNode));
I->val = 'I';
// 创建节点J
TreeNode *J = (TreeNode*)malloc(sizeof(TreeNode));
J->val = 'J';
// 构建二叉树
A->left = B;
A->right = C;
B->left = D;
B->right = E;
C->left = F;
C->right = G;
D->left = H;
D->right = I;
E->left = J;
E->right = NULL;
F->left = NULL;
F->right = NULL;
G->left = NULL;
G->right = NULL;
H->left = NULL;
H->right = NULL;
I->left = NULL;
I->right = NULL;
J->left = NULL;
J->right = NULL;
return A;
}
// 前序遍历二叉树
void preorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%c ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main() {
// 创建二叉树
TreeNode *root = createTree();
// 前序遍历二叉树
printf("前序遍历结果为:");
preorderTraversal(root);
return 0;
}
```
输出结果为:
```
前序遍历结果为:A B D H I E J C F G
```
阅读全文