用C语言写出非递归的方法实现对给定二叉树的先序和层序遍历算法,并给出一组数据
时间: 2023-06-16 15:06:13 浏览: 112
C语言实现二叉树的前序、中序、后续遍历(非递归法)
3星 · 编辑精心推荐
先序遍历的非递归实现:
```c
void preOrderTraversal(BiTree root) {
if (root == NULL) {
return;
}
Stack stack;
initStack(&stack);
push(&stack, root);
while (!isEmptyStack(&stack)) {
BiTree node = pop(&stack);
printf("%d ", node->data);
if (node->rchild != NULL) {
push(&stack, node->rchild);
}
if (node->lchild != NULL) {
push(&stack, node->lchild);
}
}
}
```
层序遍历的非递归实现:
```c
void levelOrderTraversal(BiTree root) {
if (root == NULL) {
return;
}
Queue queue;
initQueue(&queue);
enqueue(&queue, root);
while (!isEmptyQueue(&queue)) {
BiTree node = dequeue(&queue);
printf("%d ", node->data);
if (node->lchild != NULL) {
enqueue(&queue, node->lchild);
}
if (node->rchild != NULL) {
enqueue(&queue, node->rchild);
}
}
}
```
下面给出一组数据作为示例:
```
1
/ \
2 3
/ \ / \
4 5 6 7
```
对应的二叉树可以用以下代码构建:
```c
BiTree createTree() {
BiTree root = (BiTree)malloc(sizeof(TreeNode));
root->data = 1;
root->lchild = (BiTree)malloc(sizeof(TreeNode));
root->lchild->data = 2;
root->rchild = (BiTree)malloc(sizeof(TreeNode));
root->rchild->data = 3;
root->lchild->lchild = (BiTree)malloc(sizeof(TreeNode));
root->lchild->lchild->data = 4;
root->lchild->rchild = (BiTree)malloc(sizeof(TreeNode));
root->lchild->rchild->data = 5;
root->rchild->lchild = (BiTree)malloc(sizeof(TreeNode));
root->rchild->lchild->data = 6;
root->rchild->rchild = (BiTree)malloc(sizeof(TreeNode));
root->rchild->rchild->data = 7;
return root;
}
```
使用先序遍历和层序遍历函数,对以上二叉树进行遍历,输出结果如下:
```
先序遍历:1 2 4 5 3 6 7
层序遍历:1 2 3 4 5 6 7
```
阅读全文