二叉树基于C++的具体实现
二叉树的基本组成单位:Binary Node----BinNode
基本成员:
数据域:data
引用域:lChild, parent, rChild
其他指标:hieght, npl, color
笼统的称每个节点占用的空间为一个位置。
则可以定义:#define BinNodePosi(T) BinNode<T>*
函数接口:
- size()用于统计节点后代总数,或称其子树的规模。
- insertAsLC(), insertAsRC()分别用于擦汗如当前节点的左右孩子节点。(动态操作)
- succ()返回当前节点(中序遍历意义下)的直接后继。
insertAsLC():
template <typename T> BinNodePosi(T) BinNode<T>::insertAsLC(T const & e)
{ retrun lChild = new BinNode( e, this ); }
常数时间,O(1)。
size():
template <typename T>
int BinNode<T>::size(){
int s = 1;//计入本身
if (lChild) s += lChild->size();
if (rChild) s += rChile->size();
return s;
}
或者
template <typename T>
int size(BinNode<T> node){
if (!node) return 0;//空子树规模为0
return 1+size(node->lChild)+size(node->RChild);
}
需要遍历所有节点,线性时间O(n)。
二叉树的类定义
保护成员:
_size规模
_root根节点
updateHeight(x)更新节点x的高度,这里定义为虚函数,方便后续不同类型的二叉树重写其具体实现。
virtual int updateHeight( BinNodePosi(T) x );
相似的,updateHeightAbove(x)更新节点x及其祖先的高度
开放成员:
size()返回树的规模
empty()判空
root()返回树的树根节点
分别返回三个对应的保护成员变量
另外还需要设置并实现子树的拼接、删除和分离接口以及遍历接口。
高度更新函数的实现:
1.首先通过宏定义,将常规高度与退化情况的高度统一:
#define stature(p) ((p) ? (p)->height : -1)//空指针(对应空子树)返回-1
int BinTree<T>::updateHeight( BinNodePosi(T) x ){
return x->height = 1 + max( stature( x->lChild ), stature( x-> rChild ) );//对任意节点,其高度 = 左子树与右子树中高度更高者 + 1
}//此处采用常规二叉树规则,O(1)
而当某一节点的高度改变时,很可能祖先的高度也随之改变,于是我们需要实现一个能够一次性修改全部祖先的函数。
template <typename T>//更新v以及其历代祖先的高度
void BinTree<T>::updateHeightAbove(BinNodePosi(T) x ){
while (x) //可优化,一旦高度未改变可及时终止
{updateHeight(x); x = x-> parent}
}//复杂度O( n = depth(x) )
复杂度O( n = depth(x) )。