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");
}