使用c语言实现二叉树的先序的遍历、中序的遍历、后序的遍历
时间: 2023-07-23 11:15:00 浏览: 123
以下是使用C语言实现二叉树的先序遍历、中序遍历和后序遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结点
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
// 创建二叉树
struct TreeNode* createTree(int val) {
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = val;
root->left = NULL;
root->right = NULL;
return root;
}
// 构建二叉树
struct TreeNode* buildTree(int* preorder, int inorder[], int preStart, int preEnd, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) {
return NULL;
}
int rootVal = preorder[preStart];
int rootIndex = inStart;
while (inorder[rootIndex] != rootVal) {
rootIndex++;
}
int leftLen = rootIndex - inStart;
struct TreeNode* root = createTree(rootVal);
root->left = buildTree(preorder, inorder, preStart + 1, preStart + leftLen, inStart, rootIndex - 1);
root->right = buildTree(preorder, inorder, preStart + leftLen + 1, preEnd, rootIndex + 1, inEnd);
return root;
}
// 先序遍历
void preOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%d ", root->val);
inOrder(root->right);
}
// 后序遍历
void postOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(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};
struct TreeNode* root = buildTree(preorder, inorder, 0, 6, 0, 6);
printf("先序遍历结果:");
preOrder(root);
printf("\n");
printf("中序遍历结果:");
inOrder(root);
printf("\n");
printf("后序遍历结果:");
postOrder(root);
printf("\n");
return 0;
}
```
在上面的代码中,我们首先定义了二叉树结点结构体`TreeNode`,然后实现了一个`createTree`函数,该函数用于创建二叉树结点。接着,我们实现了一个`buildTree`函数,该函数用于根据先序遍历数组和中序遍历数组构建二叉树。最后,我们分别实现了先序遍历、中序遍历和后序遍历的函数,最后在主函数中调用这些函数进行遍历。
阅读全文