假设二叉树采用二叉链存储结构,设计二叉树的先序遍历、中序遍历、后序通历和层次遍历算法;并用相关数据进行测试。用c语言写
时间: 2024-02-05 08:11:49 浏览: 168
二叉树的结构体定义如下:
```c
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
```
先序遍历算法如下:
```c
void preorder(TreeNode *root) {
if (root) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
```
中序遍历算法如下:
```c
void inorder(TreeNode *root) {
if (root) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
```
后序遍历算法如下:
```c
void postorder(TreeNode *root) {
if (root) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
```
层次遍历算法如下:
```c
void levelorder(TreeNode *root) {
if (!root) {
return;
}
Queue *q = createQueue();
enqueue(q, root);
while (!isEmpty(q)) {
TreeNode *node = dequeue(q);
printf("%d ", node->data);
if (node->left) {
enqueue(q, node->left);
}
if (node->right) {
enqueue(q, node->right);
}
}
destroyQueue(q);
}
```
其中,`Queue` 是一个队列,可以使用数组或链表实现。`createQueue` 创建一个队列,`enqueue` 入队,`dequeue` 出队,`isEmpty` 判断队列是否为空,`destroyQueue` 销毁队列。
测试代码如下:
```c
int main() {
TreeNode *root = createTree();
printf("先序遍历:");
preorder(root);
printf("\n");
printf("中序遍历:");
inorder(root);
printf("\n");
printf("后序遍历:");
postorder(root);
printf("\n");
printf("层次遍历:");
levelorder(root);
printf("\n");
destroyTree(root);
return 0;
}
```
其中,`createTree` 创建二叉树,`destroyTree` 销毁二叉树。测试数据可以自行定义,也可以使用下面的数据:
```
1
/ \
2 3
/ \ \
4 5 6
/ \
7 8
```
完整代码如下:
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)