標籤:pos out 節點 bubuko return 技術分享 高度 bin pre
在第(四)節擷取節點高度函數getHeight()函數的基礎上,增添並測試更新節點高度函數和更新祖輩節點高度函數:updateHight()、updateAboveHei()。在上節中,每插入一個新節點,根結點以及新節點的其它祖輩節點的高度不增加,如今這已成為過去。在插入節點函數insertAsLC()、insertAsRC()函數中,分別添加updateAboveHei(),則每次插入新的節點,都會更新祖輩的節點高度。
節點類的代碼,如第四節,不再增加。
樹的定義代碼如下:
#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
在測試程式中的樹形結構
測試代碼與第四節一樣:
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;}
我們可以看到,隨著新節點的插入,根結點的高度隨之而增加。
二叉樹執行個體學習(五)——更新節點及祖輩節點高度