前中后序建立一棵二叉树C语言
时间: 2023-06-11 14:09:20 浏览: 89
二叉树是一种非常重要的数据结构,它的每个节点最多只有两个子节点,分别称为左子节点和右子节点。下面是在 C 语言中实现二叉树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树的节点结构体
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
// 前序遍历构建二叉树
struct TreeNode* buildTree_preorder() {
int val;
scanf("%d", &val);
if (val == -1) { // 如果输入为 -1,则返回 NULL
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = val;
root->left = buildTree_preorder();
root->right = buildTree_preorder();
return root;
}
// 中序遍历构建二叉树
struct TreeNode* buildTree_inorder() {
int val;
scanf("%d", &val);
if (val == -1) { // 如果输入为 -1,则返回 NULL
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left = NULL;
root->right = NULL;
root->val = val;
root->left = buildTree_inorder();
root->right = buildTree_inorder();
return root;
}
// 后序遍历构建二叉树
struct TreeNode* buildTree_postorder() {
int val;
scanf("%d", &val);
if (val == -1) { // 如果输入为 -1,则返回 NULL
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left = buildTree_postorder();
root->right = buildTree_postorder();
root->val = val;
return root;
}
// 前序遍历打印二叉树
void printTree_preorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
printTree_preorder(root->left);
printTree_preorder(root->right);
}
// 中序遍历打印二叉树
void printTree_inorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printTree_inorder(root->left);
printf("%d ", root->val);
printTree_inorder(root->right);
}
// 后序遍历打印二叉树
void printTree_postorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printTree_postorder(root->left);
printTree_postorder(root->right);
printf("%d ", root->val);
}
int main() {
struct TreeNode* root_preorder = buildTree_preorder(); // 前序遍历构建二叉树
printf("Preorder traversal: ");
printTree_preorder(root_preorder); // 前序遍历打印二叉树
printf("\n");
struct TreeNode* root_inorder = buildTree_inorder(); // 中序遍历构建二叉树
printf("Inorder traversal: ");
printTree_inorder(root_inorder); // 中序遍历打印二叉树
printf("\n");
struct TreeNode* root_postorder = buildTree_postorder(); // 后序遍历构建二叉树
printf("Postorder traversal: ");
printTree_postorder(root_postorder); // 后序遍历打印二叉树
printf("\n");
return 0;
}
```
在上述代码中,我们使用了三个不同的函数来分别实现前序遍历、中序遍历和后序遍历构建二叉树。在每个函数中,我们首先读入一个数字,如果这个数字是 -1,说明这个节点为空,返回 NULL。否则,我们创建一个新的二叉树节点,并递归地构建它的左子树和右子树。最后,我们返回这个节点的指针。在打印二叉树时,我们同样使用了三个不同的函数来实现前序遍历、中序遍历和后序遍历。
阅读全文