用c语言编写程序,已知一棵二叉树的先序和中序,创建这棵二叉树,并输出后序遍历的顺序
时间: 2023-05-22 15:04:43 浏览: 117
非常感谢你的问题!下面是用C语言创建一棵二叉树的代码,以及输出后序遍历的代码:
```
#include <stdio.h>
#include <stdlib.h>
/* 树节点的定义 */
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
/* 递归函数创建二叉树 */
TreeNode* buildTree(int* preorder, int prestart, int preend, int* inorder, int instart, int inend) {
if (prestart > preend || instart > inend) {
return NULL; // 递归结束
}
int root_val = preorder[prestart];
int i;
for (i = instart; i <= inend; i++) {
if (inorder[i] == root_val) {
break; // 在中序遍历中找到根节点
}
}
int left_count = i - instart;
int right_count = inend - i;
TreeNode* root = (TreeNode*) malloc(sizeof(TreeNode));
root->val = root_val;
root->left = buildTree(preorder, prestart + 1, prestart + left_count, inorder, instart, i - 1);
root->right = buildTree(preorder, preend - right_count + 1, preend, inorder, i + 1, inend);
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, 7};
int inorder[] = {4, 2, 5, 1, 6, 3, 7};
int len = sizeof(preorder) / sizeof(int);
TreeNode* root = buildTree(preorder, 0, len - 1, inorder, 0, len - 1);
printf("后序遍历的顺序: ");
postorderTraversal(root);
return 0;
}
```
希望我的回答对您有帮助!
阅读全文