目录
二叉树
特性
满二叉树
*完全二叉树
完全二叉树的框架
完全二叉树的遍历
二叉树
二叉树是每个节点最多有两个子树的有序树(度<=2)
表现形式
1.空树
2.丘(只有根节点)
3.乒(只有左子树)
4.乓(只有右子树)
5.兵(既有左子树又有右子树)
特性
1.二叉树的每个节点最多只有两颗子树
2.二叉树的子树有左右之分,次序不可颠倒
3.二叉树的第i层至多有2的i-1次方个节点
4.深度为K的二叉树至多有2^(k)-1个节点
5.任意一颗二叉树,度为2的节点数为n,度为0的节点数为m,m=n+1
满二叉树
二叉树中第i层的节点数必须为2的i次方个结点
二叉树如果高度为K,则这个二叉树的节点数必须为2的(k+1)次方-1个
满二叉树不存在度为1的节点,每一个分支节点都有两颗高度一致的二叉树
*完全二叉树
满二叉树是完全二叉树,完全二叉树不一定是满二叉树
下标规律
实现 顺序+非线性
完全二叉树的框架
template
class CMYTree_arr
{
private:
T *pBuff; //数据域
size_t len; //数据量
size_t MAXSize; //最大空间
public :
CMYTree_arr();
~CMYTree_arr();
public:
void clear(); //清除函数
bool find(T const& findVal) const;//查找
void appEndNode(T const& data); //添加
void initTreeArr(T arr[], int Length);//用数组初始化
T GetParentVal(int const & index)const;//查找父节点
///查找左右子树
T GetLChildVal(int const& index)const;//查找左子树
T GetRChildVal(int const& index)const;//查找右子树
void PrintTree();//遍历树
private:
void _PrintTree(int ArrIndex);//遍历递归
int _find(T const& findVal)const; //内部函数
};
实现
templateT CMYTree_arr ::GetParentVal(int const & index)const//查找父节点 { if (pBuff == nullptr) { throw"内容为空"; } if ((index - 1)<0 || (index - 1)>(len - 1)) { throw"访问越界"; } return pBuff[((index - 1) - 1) >> 1]; } template void CMYTree_arr ::initTreeArr(T arr[], int Length)//用数组初始化 { //初始化前先清空数组 clear(); if (Length > 0) { MAXSize = len = Length; pBuff = new T[Length]; for (size_t i = 0; i < len; i++) { pBuff[i] = arr[i]; } } } template void CMYTree_arr ::appEndNode(T const& data)//添加 { //扩容 if (len >= MAXSize) { MAXSize += (MAXSize >> 1) > 1 ? (MAXSize >> 1) : 1; T *pTemp = new T[MAXSize]; for (size_t i = 0; i < len; i++) { pTemp[i] = pBuff[i]; } if (pBuff) delete[] pBuff; pBuff = pTemp; } //扩容完成 pBuff[len++] = data; } template int CMYTree_arr ::_find(T const& findVal)const { for (size_t i = 0; i < len; i++)//层次遍历 { if (pBuff[i] == findVal) return i; } return -1; } template bool CMYTree_arr ::find(T const& findVal) const { return _find(findVal) != -1; } template void CMYTree_arr ::clear() { if (pBuff) delete[] pBuff; pBuff = nullptr; len = MAXSize = 0; } template CMYTree_arr ::~CMYTree_arr() { clear(); } template CMYTree_arr ::CMYTree_arr() { pBuff = nullptr; len = MAXSize = 0; }
完全二叉树的遍历
1).先序(根左右)
2).中序(左根右)
3).后序(左右根)
templatevoid CMYTree_arr ::_PrintTree(int ArrIndex)//遍历树递归 { if (ArrIndex<(int)len&&ArrIndex>-1) { _PrintTree(2 * ArrIndex + 1);//遍历左子树 _PrintTree(2 * ArrIndex + 2);//遍历右子树 cout << pBuff[ArrIndex] << 't';//访问根节点 } } template void CMYTree_arr ::PrintTree()//遍历树 { return _PrintTree(0); }



