Sure enough, I'm still too weak ... This spent maths me about 5, looked at all kinds of information, to achieve a self-balancing search tree
Recommend you see this, how to write a balanced binary tree step-by-step
Http://www.cppblog.com/cxiaojia/archive/2013/07/22/187776.html
The difficulty of balancing a binary tree is how to adjust it, how to calculate the height of the tree, etc.
and recursion to solve this problem is very simple (it's not easy)
#include <iostream>using namespaceStd;typedefstructtreenode{intdata; structtreenode*Leftson; structtreenode*Rightson; intheight;} TreeNode;intMaxintAintb) { if(A >b) { returnA; } Else{ returnb; }}intGetHeight (TreeNode *root) { if(Root = =NULL) { return 0; } Else returnRoot->height;} TreeNode* ROTATINGL (TreeNode *root) {TreeNode* K2 =Root; TreeNode* K1 = root->Leftson; K2->leftson = k1->Rightson; K1->rightson =K2; K2->height = Max (GetHeight (K2->leftson), GetHeight (K2->rightson)) +1; K1->height = Max (GetHeight (K1->leftson), GetHeight (K1->rightson)) +1; returnK1;} TreeNode* ROTATINGR (TreeNode *root) {TreeNode* K2 =Root; TreeNode* K1 = root->Rightson; K2->rightson = k1->Leftson; K1->leftson =K2; K2->height = Max (GetHeight (K2->leftson), GetHeight (K2->rightson)) +1; K1->height = Max (GetHeight (K1->leftson), GetHeight (K1->rightson)) +1; returnK1;} TreeNode* ROTATINGLR (TreeNode *root) {Root->leftson = Rotatingr (root->Leftson); returnRotatingl (root);} TreeNode* ROTATINGRL (TreeNode *root) {Root->rightson = Rotatingl (root->Rightson); returnRotatingr (root);} TreeNode* Insert (treenode* root,intvalue) { if(Root = =NULL) {Root= (TreeNode *)malloc(sizeof(TreeNode)); Root->data =value; Root->leftson = Root->rightson =NULL; } Else if(Value < root->data) {Root->leftson = insert (root->Leftson, value); if(GetHeight (Root->leftson)-getheight (root->rightson) = =2){ if(Value < root->leftson->data) {Root=Rotatingl (root); } Else{root=ROTATINGLR (root); } } } Else{root->rightson = insert (root->Rightson, value); if(GetHeight (Root->rightson)-getheight (root->leftson) = =2){ if(Value > Root->rightson->data) {Root=Rotatingr (root); } Else{root=ROTATINGRL (root); }}} root->height = Max (GetHeight (Root->leftson), GetHeight (Root->rightson)) +1; returnRoot;}intMain () {intN; CIN>>N; TreeNode* Root =NULL; for(inti =0; I < n; i++){ intT; CIN>>T; Root=Insert (root, t); } cout<< root->data;}
Root of AVL Tree (25)