1代码
1.1使用递归法创建一棵树
BinTree CreateBTree(string str, int i)
{
int len;
BinTree bt;
bt = new TNode;
len = str.size();
if (i > len - 1 || i <= 0) return NULL;
if (str[i] == '#') return NULL;
bt->data = str[i];
bt->lchild = CreateBTree(str, 2 * i);
bt->rchild = CreateBTree(str, 2 * i + 1);
return bt;
}
1.2在该树上实现前、中、后序遍历
前序遍历
void PreOrder(BinTree bt)
{
if (bt != NULL)
{
cout << bt->data<<' '; //访问根结点
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
中序遍历
void InOrder(BinTree bt)
{
if (bt != NULL)
{
InOrder(bt->lchild);
cout << bt->data<<' '; //访问根结点
InOrder(bt->rchild);
}
}
后序遍历
void PostOrder(BinTree bt)
{
if (bt != NULL)
{
PostOrder(bt->lchild);
PostOrder(bt->rchild);
cout<<bt->data<<' '; //访问根结点
}
}
2完整代码
#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include<string>
using namespace std;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode {
char data;
BinTree lchild;
BinTree rchild;
};//二叉树的结构存储结构声明
BinTree CreateBTree(string str, int i);//创建二叉树
void PostOrder(BinTree bt);//后续遍历
void InOrder(BinTree bt);//中序遍历
void PreOrder(BinTree bt//先序遍历
int main()
{
string str;
cin >> str;
int i=1,j=0;
BinTree bt=CreateBTree(str,i);
printf("先序遍历:");
PreOrder(bt);
printf("\n");
printf("中序遍历:");
InOrder(bt);
printf("\n");
printf("后序遍历:");
PostOrder(bt);
printf("\n");
printf("层次遍历:");
if (bt == NULL) cout << "NULL";
else {
for (j = 0; j < str.size() - 2; j++)
if (str[j] != '#') cout << str[j] << ' ';
if (str[j] != '#') cout << str[j];
if (str[j + 1] != '#') cout << str[j + 1];
}
printf("\n");
system("pause");
return 0;
}
BinTree CreateBTree(string str, int i)
{
int len;
BinTree bt;
bt = new TNode;
len = str.size();
if (i > len - 1 || i <= 0) return NULL;
if (str[i] == '#') return NULL;
bt->data = str[i];
bt->lchild = CreateBTree(str, 2 * i);
bt->rchild = CreateBTree(str, 2 * i + 1);
return bt;
}
void PreOrder(BinTree bt)//先序遍历
{
if (bt != NULL)
{
cout << bt->data; //访问根结点
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
void InOrder(BinTree bt) //中序遍历
{
if (bt != NULL)
{
InOrder(bt->lchild);
cout << bt->data; //访问根结点
InOrder(bt->rchild);
}
}
void PostOrder(BinTree bt)//后续遍历
{
if (bt != NULL)
{
PostOrder(bt->lchild);
PostOrder(bt->rchild);
cout<<bt->data; //访问根结点
}
}
3运行结果