数据结构-树-二叉链表-前序遍历-中序遍历-后序遍历

structfun.h

//数据结构函数头文件

#include <stdio.h>
#include <iostream>
#include<string>

using std::cout;
using std::cin;
using std::string;

#define MAXSIZE 200
#define OK 1
#define ERROR 0
typedef string ElemType;


//二叉链表存储结构(二叉链表存储结构跟树的孩子兄弟表示法一样,只是firstchild改成lchild,
//,rightsib改成rchild)
typedef struct BiTNode
{
	ElemType data;
	struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

//二叉链表
//创建二叉链表(前序法)
int CreateBitTreeNode(BiTree &bitree);

//遍历二叉链表(前序法)
int BeforeFindBitTree(BiTree &bitree);

//遍历二叉链表(中根遍历)
int MidFindBitTree(BiTree &bitree);

//遍历二叉链表(后根遍历)
int AfterFindBitTree(BiTree &bitree);

structfun.cpp

#include<iostream>
#include<stdio.h>
#include<string>
#include<sstream>
#include"structfun.h"


using std::cout;
using std::cin;
using std::string;
using std::endl;
using std::ostringstream;

//4、二叉链表存储结构函数

//创建二叉链表(前序法)
int CreateBitTreeNode(BiTree &bitree)
{

	ElemType e;
	printf("请输入二叉树节点(空节点用#表示):");
	cin>>e;
	if(e=="#")
		return 1;

	bitree->data=e;

	bitree->lchild=new BiTNode();//添加孩子节点空间
	bitree->rchild=new BiTNode();//添加右兄弟空间节点

	CreateBitTreeNode(bitree->lchild);//递归孩子节点
	CreateBitTreeNode(bitree->rchild);//递归右兄弟节点
	
	return OK;
}

//遍历二叉链表(先根遍历)
int BeforeFindBitTree(BiTree &bitree)
{
	if(bitree->data=="")
	{
		printf("#");
		printf(", ");
		return 0;
	}
	printf(bitree->data.c_str());
	printf(", ");
	BeforeFindBitTree(bitree->lchild);
	BeforeFindBitTree(bitree->rchild);
	return OK;
}

//遍历二叉链表(后根遍历)
int AfterFindBitTree(BiTree &bitree)
{
	if(bitree->data=="")
	{
		printf("#");
		printf(", ");
		return 0;
	}
	AfterFindBitTree(bitree->lchild);//只是递归函数位置发生变化
	AfterFindBitTree(bitree->rchild);
	printf(bitree->data.c_str());
	printf(", ");
	return OK;
}

//遍历二叉链表(中根遍历)
int MidFindBitTree(BiTree &bitree)
{
	if(bitree->data=="")
	{
		printf("#");
		printf(", ");
		return 0;
	}
	MidFindBitTree(bitree->lchild);//只是递归函数位置发生变化
	printf(bitree->data.c_str());
	printf(", ");
	
	MidFindBitTree(bitree->rchild);
	return OK;
}

main.cpp

#include<iostream>
#include<stdio.h>
#include <stdlib.h>
#include<string>
#include"structfun.h"

using std::string;
using std::printf;
using std::scanf;
using std::endl;
using std::to_string;


void main()
{

//4、二叉树二叉链表及二叉树的前序,中序,后序遍历

BiTree bitree;//定义二叉树

bitree=new BiTNode();

CreateBitTreeNode(bitree);

//前序遍历bitree二叉树
printf("二叉链表的前序遍历:");
BeforeFindBitTree(bitree);

//遍历二叉链表(中根遍历)
printf("\n二叉链表的中序遍历:");
MidFindBitTree(bitree);

printf("\n二叉链表的后序遍历:");
AfterFindBitTree(bitree);
system("pause");
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值