二叉树的基本实现
顺序存储结构
/* 二叉树的顺序存储表示 */
#define MAX_TREE_SIZE 100 /* 二叉树的最大节点数 */
typedef TElemType SqBiTree[MAX_TREE_SIZE]; /* 0号单元存储根节点 */
typedef struct
{
int level,order; /* 即节点的层(按[满二叉树]计算) */
}position;
链式存储结构
/* 二叉树的二叉联表存储表示 */
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild,*rchild; /* 左右儿子指針 */
}BiTNode,*BiTree;
/* 二叉树的三叉链表存储表示 */
typedef struct BiTPNode
{
TElemType data;
struct BiTPNode *parent,*lchild,*rchild; /* 父、左右儿子指針 */
}BiTPNode,*BiPTree;
基本实现
//二叉树 节点结构
template<class T>
struct BinaryTreeNode
{
typedef BinaryTreeNode<T>* Treepoint ;
BinaryTreeNode(const T& data)
:_data(data)
, pLeft(NULL)
, pRight(NULL)
{}
T _data;
Treepoint pLeft;
Treepoint pRight;
};
//二叉树的基本操作
template<class T>
class BinaryTree
{
public:
BinaryTree()
:_pRoot(NULL)
{}
BinaryTree(T arr[], size_t sz)
{
size_t index = 0;
_CreatNode(_pRoot, arr, sz, index);
}
BinaryTree(const BinaryTree<T>& t)//拷贝构造
{
_pRoot = _CopyTree(t._pRoot);
}
BinaryTreeNode<T>& operator=(const BinaryTree<T>& t) //赋值运算符重载
{
if (this != &t)
{
_Destroy(this->_pRoot);
this->_pRoot = _CopyTree(t._pRoot);
}
return *this;
}
~BinaryTree() //析构函数
{
if (this != NULL)
{
_Destroy(this->_pRoot);
}
}
private:
BinaryTreeNode<T>* _pRoot;
protected:
void _CreatNode(BinaryTreeNode<T>*& Root, T arr[], size_t sz, size_t& index)//创建
{ //传的是引用 //引用
if (index < sz && arr[index] != '?')
{
//前序遍历 :创建过程 根-左-右
Root = new BinaryTreeNode<T>(arr[index]);
_CreatNode(Root->pLeft, arr, sz, ++index);
_CreatNode(Root->pRight, arr, sz, ++index);
}
}
BinaryTreeNode<T>* _CopyTree(const BinaryTreeNode<T>* Root) //拷贝
{
BinaryTreeNode<T>* NewRoot = NULL;
if (Root != NULL)
{
NewRoot = new BinaryTreeNode<T>(Root->_data);
NewRoot->pLeft = _CopyTree(Root->pLeft);
NewRoot->pRight = _CopyTree(Root->pRight);
}
return NewRoot;
}
void _Destroy(BinaryTreeNode<T>*& Root) //删除顺序 左-右-根
{
if (Root != NULL)
{
_Destroy(Root->pLeft);
_Destroy(Root->pRight);
// _Destroy(Root);
delete Root;
Root = NULL;
}
}
};