已知一个二叉树的前序遍历序列和中序遍历序列,求其后序遍历序列。c语言
时间: 2023-12-18 17:46:50 浏览: 121
代码实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode{
int val; // 节点值
struct TreeNode* left; // 左子节点
struct TreeNode* right; // 右子节点
}TreeNode;
TreeNode* buildTree(int* preorder, int* inorder, int preorderStart, int preorderEnd, int inorderStart, int inorderEnd);
void postorderTraversal(TreeNode* root);
int main(){
int preorder[] = {1, 2, 4, 5, 3, 6, 7}; // 前序遍历序列
int inorder[] = {4, 2, 5, 1, 6, 3, 7}; // 中序遍历序列
int n = sizeof(preorder) / sizeof(int); // 序列长度
TreeNode* root = buildTree(preorder, inorder, 0, n - 1, 0, n - 1); // 构建二叉树
printf("后序遍历序列为:");
postorderTraversal(root); // 后序遍历输出
return 0;
}
// 根据前序遍历序列和中序遍历序列构建二叉树
TreeNode* buildTree(int* preorder, int* inorder, int preorderStart, int preorderEnd, int inorderStart, int inorderEnd){
if(preorderStart > preorderEnd){
return NULL;
}
int rootVal = preorder[preorderStart];
int index = inorderStart;
while(inorder[index] != rootVal){
index++;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = rootVal;
root->left = buildTree(preorder, inorder, preorderStart + 1, preorderStart + index - inorderStart, inorderStart, index - 1);
root->right = buildTree(preorder, inorder, preorderStart + index - inorderStart + 1, preorderEnd, index + 1, inorderEnd);
return root;
}
// 后序遍历输出
void postorderTraversal(TreeNode* root){
if(root == NULL){
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
```
阅读全文