用c语言实现以前序和中序遍历序列构建二叉树,输出前序中序后序的结果
时间: 2023-12-21 09:00:05 浏览: 114
下面是C语言实现以前序和中序遍历序列构建二叉树,并输出前序、中序、后序遍历结果的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 根据前序和中序遍历序列构建二叉树
TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
if (preorderSize == 0 || inorderSize == 0) {
return NULL;
}
// 创建根节点
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = preorder[0];
// 在中序遍历序列中找到根节点的位置
int rootIndex;
for (rootIndex = 0; rootIndex < inorderSize; rootIndex++) {
if (inorder[rootIndex] == root->val) {
break;
}
}
// 构建左子树
root->left = buildTree(preorder + 1, rootIndex, inorder, rootIndex);
// 构建右子树
root->right = buildTree(preorder + rootIndex + 1, preorderSize - rootIndex - 1,
inorder + rootIndex + 1, inorderSize - rootIndex - 1);
return root;
}
// 前序遍历
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
int main() {
int preorder[] = {1, 2, 4, 5, 3, 6};
int inorder[] = {4, 2, 5, 1, 3, 6};
int n = sizeof(preorder) / sizeof(int);
TreeNode* root = buildTree(preorder, n, inorder, n);
printf("前序遍历结果:");
preorderTraversal(root);
printf("\n");
printf("中序遍历结果:");
inorderTraversal(root);
printf("\n");
printf("后序遍历结果:");
postorderTraversal(root);
printf("\n");
return 0;
}
```
输出结果为:
```
前序遍历结果:1 2 4 5 3 6
中序遍历结果:4 2 5 1 3 6
后序遍历结果:4 5 2 6 3 1
```
阅读全文