/*Copyright (c)2015,烟台大学计算机与控制工程学院
All rights reserved.
文件名称:项目1.cbp
作 者:刘晨筱
完成日期:2015年11月2日
版 本 号:v1.0
问题描述:实现二叉树的先序、中序、后序遍历的递归算法,并对用”A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))”创建的二叉树进行测试。
请利用二叉树算法库。
输入描述:无
程序输出:测试结果。
*/
btree.h文件代码见【二叉树算法库】
btree.cpp文件代码:
#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); //访问根节点
}
}
main函数文件代码:
<pre name="code" class="cpp">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;
}
<span style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 14px; line-height: 35px;">注:在main函数中,创建的用于测试的二叉树如下—— </span><br style="box-sizing: border-box; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 14px; line-height: 35px;" /><img src="https://img-blog.csdn.net/20151019153602522" alt="这里写图片描述" title="" style="border: none; box-sizing: border-box; max-width: 602px; height: auto; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 14px; line-height: 35px;" />
运行结果:
<img src="https://img-blog.csdn.net/20151115191013842" alt="" />