c语言实现二叉树先序中序后序遍历
时间: 2023-10-13 16:23:57 浏览: 118
以下是C语言实现二叉树先序、中序、后序遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
// 创建新节点
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 构建二叉树
struct TreeNode* buildTree(int* preorder, int preStart, int preEnd, int* inorder, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) {
return NULL;
}
struct TreeNode* root = createNode(preorder[preStart]);
int rootIndex = inStart;
while (rootIndex <= inEnd && inorder[rootIndex] != preorder[preStart]) {
rootIndex++;
}
int leftSize = rootIndex - inStart;
root->left = buildTree(preorder, preStart + 1, preStart + leftSize, inorder, inStart, rootIndex - 1);
root->right = buildTree(preorder, preStart + leftSize + 1, preEnd, inorder, rootIndex + 1, inEnd);
return root;
}
// 先序遍历
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(struct 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 n = sizeof(preorder) / sizeof(preorder[0]);
struct TreeNode* root = buildTree(preorder, 0, n - 1, inorder, 0, n - 1);
printf("先序遍历: ");
preorderTraversal(root);
printf("\n中序遍历: ");
inorderTraversal(root);
printf("\n后序遍历: ");
postorderTraversal(root);
printf("\n");
return 0;
}
```
这段代码中,`buildTree` 函数用于构建二叉树,`preorderTraversal` 函数用于先序遍历二叉树,`inorderTraversal` 函数用于中序遍历二叉树,`postorderTraversal` 函数用于后序遍历二叉树。在 `main` 函数中,先构建二叉树,然后分别进行先序、中序、后序遍历并输出结果。
阅读全文