#include <iostream>
#include <string>
using namespace std;
int index = 0;
string str = "ABDH#K###E##CFI###G#J##";
template<class T>
class TreeNode
{
public:
T data;
TreeNode<T> *Lchild, *Rchild;
TreeNode();
TreeNode(T e);
};
template<class T>
TreeNode<T>::TreeNode(T e)
{
data = e;
Lchild = NULL;
Rchild = NULL;
}
template<class T>
TreeNode<T>::TreeNode()
{
Lchild = NULL;
Rchild = NULL;
}
template<class T>
class LinkTree
{
public:
TreeNode<T> *root;
LinkTree();
void CreateTree(TreeNode<T> **r);
void PreOrderTraverse(TreeNode<T> *r);
void MidOrderTraverse(TreeNode<T> *r);
void PostOrderTraverse(TreeNode<T> *r);
void Post_delete(TreeNode<T> **r);
~LinkTree();
};
template<class T>
LinkTree<T>::~LinkTree()
{
if(root == NULL)
return;
cout << "内存释放顺序:" << endl;
Post_delete(&root);
cout << endl;
cout << "内存释放完毕" << endl;
}
template<class T>
void LinkTree<T>::Post_delete(TreeNode<T> **r)
{
if(*r == NULL)
return;
Post_delete(&(*r)->Lchild);
Post_delete(&(*r)->Rchild);
cout << (*r)->data << " ";
delete *r;
}
template<class T>
void LinkTree<T>::PostOrderTraverse(TreeNode<T> *r)
{
if(r == NULL)
return;
PostOrderTraverse(r->Lchild);
PostOrderTraverse(r->Rchild);
cout << r->data << " ";
}
template<class T>
void LinkTree<T>::MidOrderTraverse(TreeNode<T> *r)
{
if(r == NULL)
return;
MidOrderTraverse(r->Lchild);
cout << r->data << " ";
MidOrderTraverse(r->Rchild);
}
template<class T>
void LinkTree<T>::PreOrderTraverse(TreeNode<T> *r)
{
if(r == NULL)
return;
cout << r->data << " ";
PreOrderTraverse(r->Lchild);
PreOrderTraverse(r->Rchild);
}
template<class T>
void LinkTree<T>::CreateTree(TreeNode<T> **r)
{
T ch;
ch = str[index++];
if(ch == '#')
*r = NULL;
else
{
*r = new TreeNode<T>;
(*r)->data = ch;
CreateTree(&(*r)->Lchild);
CreateTree(&(*r)->Rchild);
}
}
template<class T>
LinkTree<T>::LinkTree()
{
root = NULL;
}
void test02()
{
LinkTree<char> tree;
tree.CreateTree(&tree.root);
cout << "前序遍历为:" << endl;
tree.PreOrderTraverse(tree.root);
cout << endl;
cout << "中序遍历为:" << endl;
tree.MidOrderTraverse(tree.root);
cout << endl;
cout << "后序遍历为:" << endl;
tree.PostOrderTraverse(tree.root);
cout << endl;
}
int main()
{
test02();
system("pause");
return 0;
}
|