Basic Realization of the BinaryTree
环境: Codeblocks
实现二叉树展示:
头文件 main.cpp
//Written by Xuebi
//本程序先构建模板类简单二叉树,并实现先序,中序,后序,层序历遍。
#include <iostream>
#include "Tree.h"
using namespace std;
int main()
{
TreeNode<char> Plus('+');
TreeNode<char> moins('-');
TreeNode<char> fois('*');
TreeNode<char> divise('/');
TreeNode<char> E('E');
TreeNode<char> D('D');
TreeNode<char> C('C');
TreeNode<char> B('B');
TreeNode<char> A('A');
BinaryTree<char> BT(&Plus);
Plus.Leftchild=&moins;
Plus.Rightchild=&E;
moins.Leftchild=&fois;
moins.Rightchild=&D;
fois.Leftchild=&divise;
fois.Rightchild=&C;
divise.Leftchild=&A;
divise.Rightchild=&B;
cout<<"Firstly, show the Preorder: ";
BT.PreOrder();
cout<<endl;
cout<<"Secondly, show the Inorder: ";
BT.InOrder();
cout<<endl;
cout<<"Thirdly, show the Postorder: ";
BT.PostOrder();
cout<<endl;
cout<<"Fourthly, show the Levelorder: ";
BT.LevelOrder();
cout<<endl;
}
头文件 Tree.h
#ifndef _TREE_H_
#define _TREE_H_
#include <queue>
template<class T>
class BinaryTree;
template <class T>
class TreeNode
{
friend BinaryTree<T>;//友元函数啊!!!!记得带<T>
public:
TreeNode(T element):Data(element),Leftchild(0),Rightchild(0){};
TreeNode<T>*Leftchild;
TreeNode<T>*Rightchild;
T Data;
};
template <class T>
class BinaryTree
{
private:
TreeNode<T>*Head;
public:
BinaryTree(TreeNode<T>*element):Head(element){};
T Visit(TreeNode<T>*current);
void PreOrder();
void PreOrder(TreeNode<T>*current);
void InOrder();
void InOrder(TreeNode<T>*current);
void PostOrder();
void PostOrder(TreeNode<T>*current);
void LevelOrder();
};
template <class T>
T BinaryTree<T>::Visit(TreeNode<T>*current)
{
return current->Data;
}
template <class T>
void BinaryTree<T>::InOrder()
{
InOrder(Head);
}
template <class T>
void BinaryTree<T>::InOrder(TreeNode<T>*current)
{
if(current)
{
InOrder(current->Leftchild);
std::cout<<Visit(current)<<" ";
InOrder(current->Rightchild);
}
}
template <class T>
void BinaryTree<T>::PreOrder()
{
PreOrder(Head);
}
template <class T>
void BinaryTree<T>::PreOrder(TreeNode<T>*current)
{
if(current)
{
std::cout<<Visit(current)<<" ";
PreOrder(current->Leftchild);
PreOrder(current->Rightchild);
}
}
template <class T>
void BinaryTree<T>::PostOrder()
{
PostOrder(Head);
}
template <class T>
void BinaryTree<T>::PostOrder(TreeNode<T>*current)
{
if(current)
{
PostOrder(current->Leftchild);
PostOrder(current->Rightchild);
std::cout<<Visit(current)<<" ";
}
}
template <class T>
void BinaryTree<T>::LevelOrder()
{
std::queue<TreeNode<T>*> p;
TreeNode<T>*current=Head;
while(current)
{
std::cout<<Visit(current)<<" ";
if(current->Leftchild)
p.push(current->Leftchild);
if(current->Rightchild)
p.push(current->Rightchild);
if(p.empty())
return;
current=p.front();
p.pop();
}
}
#define _TREE_H_
#endif // _TREE_H_