AVL树节点声明
1 2 3 4 5 6 7 8 9 10 11 12 13
| static const int ALLOWED_IMBALANCE = 1; struct AvlNode { int element; AvlNode* left; AvlNode* right; int height;
AvlNode(const int& e, AvlNode* lt, AvlNode* rt, int h = 0) :element(e),left(lt),right(rt),height(h){} AvlNode(int && e,AvlNode*lt,AvlNode*rt,int h=0) :element(move(e)),left(lt),right(rt),height(h){} };
|
函数
height
1 2 3 4
| int height(AvlNode* t) { return t == nullptr ? -1 : t->height; }
|
rotatedWithLeftChild
1 2 3 4 5 6 7 8 9
| void rotatedWithLeftChild(AvlNode*& k2) { AvlNode* k3 = k2->left; k2->left = k3->right; k3->right = k2; k2->height = max(height(k2->left), height(k2->right)) + 1; k3->height = max(height(k3->left), height(k3->right)) + 1; k2 = k3; }
|
rotatedWithRightChild
1 2 3 4 5 6 7 8 9
| void rotatedWithRightChild(AvlNode*& k2) { AvlNode* k1 = k2->right; k2->right = k1->left; k1->left = k2; k2->height = max(height(k2->left), height(k2->right)) + 1; k1->height = max(height(k1->left), height(k1->right)) + 1; k2 = k1; }
|
doubleWithLeftChild
1 2 3 4 5
| void doubleWithLeftChild(AvlNode*& k3) { rotatedWithRightChild(k3->left); rotatedWithLeftChild(k3); }
|
doubleWithRightChild
1 2 3 4 5
| void doubleWithRightChild(AvlNode*& k3) { rotatedWithLeftChild(k3->left); rotatedWithRightChild(k3); }
|
balance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| void balance(AvlNode*& t) { if (t == nullptr) { return; } if (height(t->left) - height(t->right) > ALLOWED_IMBALANCE) { if (height(t->left->left) >= height(t->left->right)) { rotatedWithLeftChild(t); } else { doubleWithLeftChild(t); } } else if (height(t->right) - height(t->left) > ALLOWED_IMBALANCE) { if (height(t->right->right) >= height(t->right->left)) { rotatedWithRightChild(t); } else doubleWithRightChild(t); } t->height = max(height(t->left), height(t->right)) + 1; }
|
insert
1 2 3 4 5 6 7 8 9 10
| void insert(const int& x, AvlNode*& t) { if (t == nullptr) t = new AvlNode(x, nullptr, nullptr); else if (x < t->element) insert(x, t->left); else if (x > t->element) insert(x, t->right); balance(t); }
|
remove
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| void remove(const int& x, AvlNode*& t) { if (t == nullptr)return; if (x < t->element) remove(x, t->left); else if (x > t->element) remove(x, t->right); else if (t->left != nullptr && t->right != nullptr) { t->element = findMin(t->right)->element; remove(t->element, t->right); } else { AvlNode* oldNode = t; t = (t->left != nullptr) ? t->left : t->right; delete oldNode; } balance(t); }
|
树的遍历
以排列顺序打印根在t处的子树的内部方法(中序遍历)
1 2 3 4 5 6 7 8 9
| void printTree(BinaryNode* t,ostream& out) const { if(t!=nullptr) { printTree(t->left,out); out<<t->element<<endl; printTree(t->right,out); } }
|
按排列顺序打印树的内容
1 2 3 4 5 6 7
| void printTree(ostream& out=cout)const { if(isEmpty()) out<<"Empty tree"<<endl; else printTree(root,out); }
|