写一个c语言程序,设计二叉树的先序遍历、中序遍历、后序遍历和次遍历算法;并用相关数据进行测试。
时间: 2023-05-14 12:05:39 浏览: 149
实现先序,中序和后序遍历的二叉树遍历程序
5星 · 资源好评率100%
非常感谢您的问题!以下是一个C语言程序,用于实现二叉树的先序遍历、中序遍历、后序遍历和层次遍历算法,并使用相关数据进行测试。
```
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//创建二叉树
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
//先序遍历
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* node = queue[front++];
printf("%d ", node->val);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
int main() {
printf("请输入二叉树的节点值(-1表示空节点):\n");
TreeNode* root = createTree();
printf("先序遍历结果:");
preOrder(root);
printf("\n中序遍历结果:");
inOrder(root);
printf("\n后序遍历结果:");
postOrder(root);
printf("\n层次遍历结果:");
levelOrder(root);
printf("\n");
return 0;
}
```
测试数据:
```
输入:1 2 -1 -1 3 -1 -1
输出:
先序遍历结果:1 2 3
中序遍历结果:2 1 3
后序遍历结果:2 3 1
层次遍历结果:1 2 3
```
希望这个程序能够帮助您!
阅读全文