用C写一个二叉树求先序遍历中序遍历后序遍历层次遍历
时间: 2024-05-07 16:23:41 浏览: 127
C语言实现二叉树的前序、中序、后续遍历(递归法)
下面是使用C语言实现二叉树的先序遍历、中序遍历、后序遍历和层次遍历的代码。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建新节点
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 先序遍历
void preOrder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val); // 输出节点值
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%d ", root->val); // 输出节点值
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->val); // 输出节点值
}
// 层次遍历
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front != rear) {
TreeNode* cur = queue[front++];
printf("%d ", cur->val); // 输出节点值
if (cur->left != NULL) {
queue[rear++] = cur->left;
}
if (cur->right != NULL) {
queue[rear++] = cur->right;
}
}
}
int main() {
// 创建二叉树
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
printf("先序遍历: ");
preOrder(root);
printf("\n");
printf("中序遍历: ");
inOrder(root);
printf("\n");
printf("后序遍历: ");
postOrder(root);
printf("\n");
printf("层次遍历: ");
levelOrder(root);
printf("\n");
return 0;
}
```
输出结果为:
```
先序遍历: 1 2 4 5 3 6 7
中序遍历: 4 2 5 1 6 3 7
后序遍历: 4 5 2 6 7 3 1
层次遍历: 1 2 3 4 5 6 7
```
阅读全文