C语言建立一棵二叉树,并实现前序、中序和后序遍历这棵二叉树。生成代码
时间: 2024-05-01 11:07:51 浏览: 10
很高兴为您提供代码:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* create_node(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
struct TreeNode* build_tree(int* inorder, int inorder_start, int inorder_end, int* postorder, int postorder_start, int postorder_end) {
if (inorder_start > inorder_end) return NULL;
int root_val = postorder[postorder_end];
struct TreeNode* root = create_node(root_val);
int i;
for (i = inorder_start; i <= inorder_end; i++) {
if (inorder[i] == root_val) break;
}
int left_size = i - inorder_start;
root->left = build_tree(inorder, inorder_start, i - 1, postorder, postorder_start, postorder_start + left_size - 1);
root->right = build_tree(inorder, i + 1, inorder_end, postorder, postorder_start + left_size, postorder_end - 1);
return root;
}
void pre_order(struct TreeNode* root) {
if (root != NULL) {
printf("%d ", root->val);
pre_order(root->left);
pre_order(root->right);
}
}
void in_order(struct TreeNode* root) {
if (root != NULL) {
in_order(root->left);
printf("%d ", root->val);
in_order(root->right);
}
}
void post_order(struct TreeNode* root) {
if (root != NULL) {
post_order(root->left);
post_order(root->right);
printf("%d ", root->val);
}
}
int main() {
int inorder[] = { 4, 2, 5, 1, 6, 3 };
int postorder[] = { 4, 5, 2, 6, 3, 1 };
int size = sizeof(inorder) / sizeof(inorder[0]);
struct TreeNode* root = build_tree(inorder, 0, size - 1, postorder, 0, size - 1);
printf("Pre-order: ");
pre_order(root);
printf("\nIn-order: ");
in_order(root);
printf("\nPost-order: ");
post_order(root);
printf("\n");
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)