On the basis of the node height function getheight () function in section (iv), add and test the Update node height function and update the ancestor node height function: Updatehight (), Updateabovehei (). In the previous section, the height of each new node inserted, the root node, and the other ancestors of the new node did not increase, which is now a past. In the Insert Node function INSERTASLC (), insertasrc () function, add Updateabovehei () separately, each time a new node is inserted, the ancestor's node height is updated.
The code for the node class, such as section fourth, is no longer incremented.
The tree definition code is as follows:
#ifndef Bintree#defineBintree#include<binnode.h>Template<typename t>classbintree{ Public: int_size; Binnodeposi (T) _root;//root node pointer intgethight (Binnodeposi (T) x) {intL_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; } returnL_hight>r_hight?L_hight:r_hight; } intMaxintAintb) {if(a>b)returnA; Else returnb; } ///Update node height function updateheight ()///and update ancestor node height function updateaboveheight () Virtual intUpdateheight (Binnodeposi (T) x)//Update the height of node x { returnx->height=1+max (Gethight (X->LC), Gethight (x->RC)); } voidUpdateaboveheight (binnode<t> *x)//with the height of the new node x and its ancestors { while(x) {updateheight (x);//Update the current node height firstx=x->parent;//then update the ancestor node height } } Public: Bintree (): _size (0), _root (NULL) {}intSize ()Const{return_size;}//gets the size of the tree, which is the total number of nodes BOOLEmpty () {return!_root;}//Determine if the tree is emptyBinnodeposi (T) root ()Const{return_root;}//Gets the root node pointer.Binnodeposi (t) insertasroot (tConst&e) {_size=1; return_root=NewBinnode<t>(e); } binnodeposi (t) INSERTASLC (Binnodeposi (t) x,tConst&e) {_size++;x->INSERTASLC (e);//x->height =gethight (x);//Replace the statement with Updateaboveheight (x);updateaboveheight (x); returnX->LC; } binnodeposi (t) insertasrc (Binnodeposi (t) x,tConst&e) {_size++;x->insertasrc (e); Updateaboveheight (x); returnX->RC; }};#endif //Bintree
The tree structure in the test program
The test code is the same as in section Fourth:
intMain () {Binnode<string>* n[6];//Array PointersBintree<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"); //test the height of the root nodeCout<<bt.gethight (n[2]) <<Endl;//bt.updateheight (bt._root);cout<<bt._root->height<<Endl; return 0;}
As we can see, the height of the root node increases with the insertion of the new node.
Binary Tree Example Learning (v)--Update node and ancestor node height