尤其注意删除单个根结点、删除有一个分支的根结点时要防止内存泄露(_root为私有成员时)
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
//结点类
template <class T>
class BinaryNode
{
public:
T data;
BinaryNode<T> *lchild;
BinaryNode<T> *rchild;
BinaryNode();
BinaryNode(T val);
private:
};
template <class T>
BinaryNode<T>::BinaryNode()
{
data = 0;
lchild = NULL;
rchild = NULL;
}
template <class T>
BinaryNode<T>::BinaryNode(T val)
{
data = val;
lchild = NULL;
rchild = NULL;
}
//二叉树类
template <class T>
class BinaryTree
{
private:
BinaryNode<T> *_root; //根结点
public:
BinaryTree(); //构造空结点
BinaryTree(const T preList[], const int size, int index, const T end); //先序构造
~BinaryTree();
BinaryNode<T>* CreateBiTree(const T preList[], const int size, int &index, const T end); //先序创建二叉树
void ClearBiTree(BinaryNode<T> *root); //销毁二叉树
void PreVisitBiTree(); //先序遍历,非递归
void MidVisitBiTree(); //中序遍历,非递归
void PostVisitBiTree(); //后序遍历,非递归
void LevelVisitBiTree();//层序遍历,非递归
void InsertTree(int val);
void DeleteTree(int val);
BinaryNode<T>* SearchTree(int val);
};
//构造空树
template <class T>
BinaryTree<T>::BinaryTree()
{
_root = NULL;
}
//先序构造二叉树
template <class T>
BinaryTree<T>::BinaryTree(const T preList[], const int size, int index, const T end)
{
_root = CreateBiTree(preList, size, index, end);
}
//析构
template <class T>
BinaryTree<T>::~BinaryTree()
{
ClearBiTree(_root);
_root = NULL;
}
//先序创建二叉树
template <class T>
BinaryNode<T>* BinaryTree<T>::CreateBiTree(const T preList[],const int size, int &index,const T end) //特别注意:index必须用引用,否则函数的两个++index将不会正常改变
{
BinaryNode<