首先,跟之前一样,先给出二叉树结点的类
template<class T>
struct binaryTreeNode
{
T element;
binaryTreeNode<T> *leftChild,//左子树
*rightChild;//右子树
//二叉树节点有三个构造函数
binaryTreeNode()
{
leftChild=rightChild=NULL;
}
binaryTreeNode(const T& theElement)
{
element=theElement;
leftChild=rightChild=NULL;
}
binaryTreeNode(const T& theElement,binaryTreeNode *theLeftChild,binaryTreeNode *theRightChild)
{
element=theElement;
leftChild=theLeftChild;
rightChild=theRightChild;
}
};
接下来是二叉树的抽象类
template<class T>
class binaryTree
{
public:
virtual ~binaryTree(){}
virtual bool empty()const =0;
virtual int size()const=0;
virtual void preOrder(void(*)(T*))=0;//前序遍历
virtual void inOrder(void(*)(T*))=0;//中序遍历
virtual void postOrder(void(*)(T*))=0;//后序遍历
virtual void levelOrder(void(*)(T*))=0;//层次遍历
};
下面阿伟嫖的书上代码,目前还是有些看不懂emm(二叉树的链式描述,继承binaryTree)
template<class T>
class linkedBinaryTree:public binaryTree<binaryTreeNode<E> >
{
private:
binaryTreeNode<E> *root;//指向根的指针
int treeSize;//树的节点个数
static void (*visit)(binaryTreeNode<E>*);//访问函数
static void preOrder(binaryTreeNode<E> *t);
static void inOrder(binaryTreeNode<E> *t);
static void postOrder(binaryTreeNode<E> *t);
static void dispose(binaryTreeNode<E> *t){delete t;}
public:
linkedBinaryTree()
{
root=NULL;
treeSize=0;
}
~linkedBinaryTree()
{
erase();
}
bool empty()const
{
return treeSize==0;
}
int size()const
{
return treeSize;
}
void preOrder(void (*theVisit)(binaryTreeNode<E>*))
{
visit=theVisit;
preOrder(root);
}
void inOrder(void (*theVisit)(binaryTreeNode<E>*))
{
visit=theVisit;
inOrder(root);
}
void postOrder(void (*theVisit)(binaryTreeNode<E>*))
{
visit=theVisit;
postOrder(root);
}
void levelOrder(void (*)(binaryTreeNode<E> *));
void erase()
{
postOrder(dispose);
root=NULL;
treeSize=0;
}
};