【二叉树遍历的递归算法】
实现二叉树的先序、中序、后序遍历的递归算法,并对用”A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))”创建的二叉树进行测试。
请利用二叉树算法库。
[参考解答]
#include <stdio.h>
#include "btree.h"
void PreOrder(BTNode *b)
{
if (b!=NULL)
{
printf("%c ",b->data);
PreOrder(b->lchild);
PreOrder(b->rchild);
}
}
void InOrder(BTNode *b)
{
if (b!=NULL)
{
InOrder(b->lchild);
printf("%c ",b->data);
InOrder(b->rchild);
}
}
void PostOrder(BTNode *b)
{
if (b!=NULL)
{
PostOrder(b->lchild);
PostOrder(b->rchild);
printf("%c ",b->data);
}
}
int main()
{
BTNode *b;
CreateBTNode(b,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
printf("二叉树b:");
DispBTNode(b);
printf("\n");
printf("先序遍历序列:\n");
PreOrder(b);
printf("\n");
printf("中序遍历序列:\n");
InOrder(b);
printf("\n");
printf("后序遍历序列:\n");
PostOrder(b);
printf("\n");
DestroyBTNode(b);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
注:在main函数中,创建的用于测试的二叉树如下——