已知二叉树前序和中序,求后序遍历,要求用C++实现
时间: 2024-04-30 08:24:10 浏览: 109
思路:
1. 根据前序遍历,找到根节点;
2. 根据中序遍历,找到根节点在中序遍历中的位置,从而确定左子树和右子树的中序遍历;
3. 根据左子树和右子树的节点数,可以在前序遍历中找到左子树和右子树的前序遍历;
4. 递归地处理左子树和右子树。
代码实现:
```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 i;
for (i = 0; i < inorderSize; i++) {
if (inorder[i] == preorder[0]) {
break;
}
}
int leftSize = i;
int rightSize = inorderSize - i - 1;
root->left = buildTree(preorder + 1, leftSize, inorder, leftSize);
root->right = buildTree(preorder + 1 + leftSize, rightSize, inorder + i + 1, rightSize);
return root;
}
// 后序遍历二叉树
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 size = sizeof(preorder) / sizeof(int);
TreeNode* root = buildTree(preorder, size, inorder, size);
postorderTraversal(root);
return 0;
}
```
运行结果:
```
4 5 2 6 3 1
```
阅读全文