用C语言按要求写出非递归的方法实现对给定二叉树的先序和层序遍历算法,并给出输入的二叉树以及结果
时间: 2024-05-10 10:17:28 浏览: 131
以下是使用C语言实现二叉树的先序遍历和层序遍历的非递归算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 定义队列最大长度
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义队列结构体
typedef struct Queue {
TreeNode* data[MAXSIZE];
int front;
int rear;
} Queue;
// 初始化队列
void initQueue(Queue* q) {
q->front = q->rear = 0;
}
// 判断队列是否为空
int isEmpty(Queue* q) {
return q->front == q->rear;
}
// 入队
void push(Queue* q, TreeNode* node) {
if ((q->rear + 1) % MAXSIZE == q->front) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = node;
q->rear = (q->rear + 1) % MAXSIZE;
}
// 出队
TreeNode* pop(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return NULL;
}
TreeNode* node = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return node;
}
// 先序遍历二叉树(非递归)
void preorderTraversal(TreeNode* root) {
// 初始化栈
TreeNode* stack[MAXSIZE];
int top = -1;
TreeNode* p = root;
while (p || top != -1) {
if (p) {
printf("%d ", p->val);
stack[++top] = p;
p = p->left;
} else {
p = stack[top--];
p = p->right;
}
}
}
// 层序遍历二叉树(非递归)
void levelTraversal(TreeNode* root) {
if (!root) {
return;
}
Queue q;
initQueue(&q);
push(&q, root);
while (!isEmpty(&q)) {
TreeNode* node = pop(&q);
printf("%d ", node->val);
if (node->left) {
push(&q, node->left);
}
if (node->right) {
push(&q, node->right);
}
}
}
// 创建二叉树
TreeNode* createTree() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
TreeNode* node1 = (TreeNode*)malloc(sizeof(TreeNode));
node1->val = 2;
TreeNode* node2 = (TreeNode*)malloc(sizeof(TreeNode));
node2->val = 3;
TreeNode* node3 = (TreeNode*)malloc(sizeof(TreeNode));
node3->val = 4;
TreeNode* node4 = (TreeNode*)malloc(sizeof(TreeNode));
node4->val = 5;
TreeNode* node5 = (TreeNode*)malloc(sizeof(TreeNode));
node5->val = 6;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
node2->right = node5;
return root;
}
int main() {
TreeNode* root = createTree();
printf("Preorder traversal: ");
preorderTraversal(root);
printf("\n");
printf("Level traversal: ");
levelTraversal(root);
printf("\n");
return 0;
}
```
上述代码中,我们使用了一个队列实现了二叉树的层序遍历,使用一个栈实现了二叉树的先序遍历。下面是程序的输出结果:
```
Preorder traversal: 1 2 4 5 3 6
Level traversal: 1 2 3 4 5 6
```
这里我们使用了如下的二叉树作为输入:
```
1
/ \
2 3
/ \ \
4 5 6
```
阅读全文