题目描述
给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘#’表示,例如AB#C##D##),建立该二叉树的二叉链式存储结构,并输出该二叉树的先序遍历、中序遍历和后序遍历结果。
A
/ \
B D
\
C
输入
第一行输入一个整数t,表示有t个二叉树
第二行起输入每个二叉树的先序遍历结果,空树用字符‘#’表示,连续输入t行。
输出
输出每个二叉树的先序遍历、中序遍历和后序遍历结果。
样例输入
2
AB#C##D##
AB##C##样例输出
ABCD
BCAD
CBDA
ABC
BAC
BCA
#include <iostream>
using namespace std;
//二叉树的链式存储结构
class Binary_tree_node
{
public:
char data; //数据域
Binary_tree_node *leftChild; //左孩子
Binary_tree_node *rightChild; //右孩子
Binary_tree_node() : leftChild(NULL), rightChild(NULL) {}
Binary_tree_node(char item, Binary_tree_node *left = NULL,
Binary_tree_node *right = NULL) : data(item), leftChild(left), rightChild(right) {}
~Binary_tree_node() {}
Binary_tree_node *&Left(void)
{
return leftChild;
}
Binary_tree_node *&Right(void)
{
return rightChild;
}
};
class Binary_tree
{
private:
Binary_tree_node *root; //根结点
int i;
void Destroy(Binary_tree_node *&t) //销毁二叉树
{
if (t != NULL && t->Left() != NULL)
{
Destroy(t->Left());
}
if (t != NULL && t->Right() != NULL)
{
Destroy(t->Right());
}
if (t != NULL)
{
delete t;
}
}
void PreOrder(Binary_tree_node *&t) //先序遍历
{
if (t != NULL)
{
cout << (t->data);
PreOrder(t->Left());
PreOrder(t->Right());
}
}
void InOrder(Binary_tree_node *&t) //中序遍历
{
if (t != NULL)
{
InOrder(t->Left());
cout << (t->data);
InOrder(t->Right());
}
}
void PostOrder(Binary_tree_node *&t) //后续遍历
{
if (t != NULL)
{
PostOrder(t->Left());
PostOrder(t->Right());
cout << (t->data);
}
}
void CreateBiTree(Binary_tree_node *&T, const char strTree[]) //先序遍历构建二叉树
{
char ch;
ch = strTree[i++];
if (ch == '0')
{
T = NULL;
}
else
{
T = new Binary_tree_node();
T->data = ch;
CreateBiTree(T->Left(), strTree);
CreateBiTree(T->Right(), strTree);
}
}
public:
Binary_tree(void) : root(NULL), i(0){};
~Binary_tree(void){};
void MakeTree(const char item, Binary_tree &left, Binary_tree &right)
{
root = new Binary_tree_node(item, left.root, right.root);
}
void MakeTree(const char strTree[])
{
i = 0;
CreateBiTree(root, strTree);
}
void Destroy(void)
{
Destroy(root);
}
void PreOrder()
{
PreOrder(root);
}
void InOrder()
{
InOrder(root);
}
void PostOrder()
{
PostOrder(root);
}
};
int main()
{
int t, i;
char strTree[80];
Binary_tree Bt;
cin >> t;
while (t--)
{
cin >> strTree;
Bt.MakeTree(strTree);
Bt.PreOrder();
cout << endl;
Bt.InOrder();
cout << endl;
Bt.PostOrder();
cout << endl;
Bt.Destroy();
}
return 0;
}