重建二叉树,给出后序中序推前序c语言
时间: 2023-06-16 08:03:57 浏览: 122
以下是给定后序遍历和中序遍历,推导出前序遍历的 C 代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 根据后序遍历和中序遍历推导出前序遍历
TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
if (inorderSize == 0 || postorderSize == 0) {
return NULL;
}
// 后序遍历的最后一个节点为根节点
int rootVal = postorder[postorderSize - 1];
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = rootVal;
root->left = NULL;
root->right = NULL;
// 在中序遍历中找到根节点的位置
int rootIndex = 0;
for (int i = 0; i < inorderSize; i++) {
if (inorder[i] == rootVal) {
rootIndex = i;
break;
}
}
// 根据根节点在中序遍历中的位置,推导出左右子树的后序遍历和中序遍历
int leftSize = rootIndex;
int rightSize = inorderSize - rootIndex - 1;
int* leftInorder = (int*)malloc(leftSize * sizeof(int));
int* rightInorder = (int*)malloc(rightSize * sizeof(int));
int* leftPostorder = (int*)malloc(leftSize * sizeof(int));
int* rightPostorder = (int*)malloc(rightSize * sizeof(int));
for (int i = 0; i < leftSize; i++) {
leftInorder[i] = inorder[i];
leftPostorder[i] = postorder[i];
}
for (int i = 0; i < rightSize; i++) {
rightInorder[i] = inorder[rootIndex + 1 + i];
rightPostorder[i] = postorder[leftSize + i];
}
// 递归构建左右子树
root->left = buildTree(leftInorder, leftSize, leftPostorder, leftSize);
root->right = buildTree(rightInorder, rightSize, rightPostorder, rightSize);
free(leftInorder);
free(rightInorder);
free(leftPostorder);
free(rightPostorder);
return root;
}
// 前序遍历二叉树
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main() {
int inorder[] = { 4, 2, 5, 1, 6, 3 };
int postorder[] = { 4, 5, 2, 6, 3, 1 };
int inorderSize = sizeof(inorder) / sizeof(int);
int postorderSize = sizeof(postorder) / sizeof(int);
TreeNode* root = buildTree(inorder, inorderSize, postorder, postorderSize);
printf("前序遍历结果:");
preorderTraversal(root);
return 0;
}
```
输出结果为:`前序遍历结果:1 2 4 5 3 6`,符合预期。
阅读全文