按先序次序输入二叉树中结点的值 c语言设计程序实现二叉树的四种遍历算法;
时间: 2023-07-16 16:15:21 浏览: 86
以下是基于链式存储结构的二叉树遍历算法的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 preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
// 层序遍历
void levelorderTraversal(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 traversal: ");
preorderTraversal(root);
printf("\n");
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\n");
printf("Postorder traversal: ");
postorderTraversal(root);
printf("\n");
printf("Levelorder traversal: ");
levelorderTraversal(root);
printf("\n");
return 0;
}
```
这里实现了四种遍历算法,分别是先序遍历、中序遍历、后序遍历和层序遍历。其中,先序遍历、中序遍历和后序遍历都是基于递归实现的,而层序遍历则是基于队列实现的。
阅读全文