在数组表示中,二叉树的元素按照其编号储存在数组的相应位置,结点为空即数组该位置的元素为0
#include<iostream>
using namespace std;
template <class T>
class Tree
{
public:
Tree(int size,T*pRoot);//创建树
~Tree();//销毁
T *searchNode(int nodeIndex);//根据索引寻找结点
bool AddNode(int nodeIndex, int direction, T *pNode);//增加结点
bool DeleteNode(int nodeIndex, T *pNode);//删除节点
void TreeTraverse();//遍历树
private:
T *m_pTree;
int m_iSize;
};
template<class T>
Tree<T>::Tree(int size,T* pRoot)
{
m_iSize = size;
m_pTree = new T[size];
for (int i = 0; i < size; i++)
{
m_pTree[i] = 0;
}
m_pTree[0] = *pRoot;
}
template<class T>
Tree<T>::~Tree()
{
delete[] m_pTree;
m_pTree = NULL;
}
template<class T>
T* Tree<T>::searchNode(int nodeIndex)
{
if (nodeIndex<0 || nodeIndex>m_iSize)
{
return NULL;
}
if (nodeIndex == 0)
{
return NULL;
}
return &m_pTree[nodeIndex];
}
template<class T>
bool Tree<T>::AddNode(int nodeIndex, int direction, T* pNode)
{
if (nodeIndex<0 || nodeIndex>=m_iSize)
{
return false;
}
if (direction == 0) //往左节点插入
{
if ((nodeIndex * 2 + 1) >= m_iSize)
{
return false;
}
if (m_pTree[(nodeIndex * 2 + 1)] != 0) //表明当前位置已有元素
{
return false;
}
m_pTree[nodeIndex * 2 + 1] = *pNode;
}
if (direction == 1) //右节点插入
{
if ((nodeIndex * 2 + 2) >= m_iSize)
{
return false;
}
if (m_pTree[(nodeIndex * 2 + 2)] != 0) //表明当前位置已有元素
{
return false;
}
m_pTree[nodeIndex * 2 + 2] = *pNode;
}
return true;
}
template<class T>
bool Tree<T>::DeleteNode(int nodeIndex, T *pNode)
{
if (nodeIndex<0 || nodeIndex >= m_iSize)
{
return false;
}
*pNode = m_pTree[nodeIndex];
m_pTree[nodeIndex] = 0;//将结点置0,即删除结点
}
template<class T>
void Tree<T>::TreeTraverse()
{
for (int i = 0; i < m_iSize; i++)
{
cout << m_pTree[i] << " ";
}
}