在第(四)節獲取節點高度函數getHeight()函數的基礎上,增添並測試更新節點高度函數和更新祖輩節點高度函數:updateHight()、updateAboveHei()。在上節中,每插入一個新節點,根結點以及新節點的其它祖輩節點的高度不增長,現在這已成爲過去。在插入節點函數insertAsLC()、insertAsRC()函數中,分別添加updateAboveHei(),則每次插入新的節點,都會更新祖輩的節點高度。node
節點類的代碼,如第四節,再也不增長。數組
樹的定義代碼以下:函數
#ifndef BINTREE #define BINTREE #include<binnode.h> template<typename T> class BinTree { public: int _size; BinNodePosi(T) _root;//根結點指針 int getHight(BinNodePosi(T) x) { int l_hight,r_hight; if(x==NULL) return -1; else if(!hasChild(*x)) { return 0; } else { l_hight = getHight(x->lc)+1; r_hight = getHight(x->rc)+1; } return l_hight>r_hight?l_hight:r_hight; } int max(int a,int b) { if(a>b) return a; else return b; } ///更新節點高度函數updateHeight() /// 以及更新祖輩節點高度函數updateAboveHeight() virtual int updateHeight(BinNodePosi(T) x)//更新節點x的高度 { return x->height=1+max(getHight(x->lc),getHight(x->rc)); } void updateAboveHeight(BinNode<T> *x)//跟新節點x及其祖先的高度 { while(x) { updateHeight(x);//先更新當前節點高度 x=x->parent;//而後更新祖輩節點高度 } } public: BinTree():_size(0),_root(NULL){} int size()const{return _size;}//獲取樹的規模,即共有多少個節點 bool empty(){return !_root;}//判斷是否爲空樹 BinNodePosi(T) root()const{return _root;}//獲取根結點指針 BinNodePosi(T) insertAsRoot(T const&e) { _size=1; return _root=new BinNode<T>(e); } BinNodePosi(T) insertAsLC(BinNodePosi(T) x,T const&e) { _size++;x->insertAsLC(e); // x->height =getHight(x);//將該語句替換爲updateAboveHeight(x); updateAboveHeight(x); return x->lc; } BinNodePosi(T) insertAsRC(BinNodePosi(T) x,T const&e) { _size++;x->insertAsRC(e); updateAboveHeight(x); return x->rc; } }; #endif // BINTREE
在測試程序中的樹形結構如圖所示測試
測試代碼與第四節同樣:spa
int main() { BinNode<string>* n[6];//數組指針 BinTree<string> bt; n[0]= bt.insertAsRoot("n0"); n[1]= bt.insertAsLC(n[0],"n1"); n[2]= bt.insertAsRC(n[0],"n2"); n[3]= bt.insertAsLC(n[1],"n3"); n[4]=bt.insertAsLC(n[2],"n4"); n[5]=bt.insertAsLC(n[4],"n5"); //測試根結點的高度 cout<<bt.getHight(n[2])<<endl; // bt.updateHeight(bt._root); cout<<bt._root->height<<endl; return 0; }
咱們能夠看到,隨着新節點的插入,根結點的高度隨之而增長。指針