AVL Tree Golang Implementation

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

#Tree


Terms:
-Tree
-Root
-Node
-Leaves
-Hierarchy, root node
-depth
-the height of the tree, the depth of the empty tree is '-1 ', the depth of the root is ' 0 ', the height of a node is ' 0 ', and the height of all the leaves is ' 0 '.


---


# #二叉树
Each node has a maximum of two children, and the empty tree is a binary tree, and the list is a special two-fork tree.


# # Two fork sorting tree (binary search tree, B-Tree)


# # Two fork Tree


# # Complete Binary tree


# # AVL Tree
The AVL tree is essentially a binary search tree (so the reader can see that the code behind me is inherited from the binary search tree), which is characterized by:


1. itself is first a binary search tree.
2. With equilibrium condition: the absolute value (balance factor) of the difference of the height of the left and right sub-tree of each node is up to 1.


For example:
```
5 5
/ \            / \
2 6 2 6
/ \   \        / \
1 4 7) 1 4
/              /
3 3
```
, the left is the AVL tree, and the right is not. Because the absolute value of the difference between the left and right sub-trees of each node of the tree on the other side is a maximum of 1, and the tree on the other side has no subtree due to node 6, the balance factor of root node 5 is 2.


Suppose that there is a node with a balance factor of 2 (in the AVL tree, the largest is 2, because the node is inserted into the tree one by one, once the imbalance in the state will be adjusted immediately, so the balance factor can not exceed 2), then you need to adjust. Since any one node has a maximum of two sons, it can only be caused by the following four cases when the height is unbalanced:


-An insertion (' LL ') of the left subtree of the left son of the node.


-An insertion (' LR ') of the right subtree of the left son of the node.


-An insertion (' RL ') of the left subtree of the right son of the node.


-An insertion (' RR ') of the right child tree of the right son of the node.


Conditions 1 and 4 are mirrored symmetry for that point, and similarly, cases 2 and 3 are also pairs of mirrored symmetry. So, theoretically there are only two cases, of course, from a programming point of view or four cases.


The first case is when inserting an "outside" condition (that is, left-left or right-right), which can be adjusted by a single rotation of the tree. The second case is the insertion of an "internal" condition (that is, a left-right case or right-left case), which is handled by a slightly more complex double rotation.




' Spin: '


# # #单旋转
Case 1 (' LL '): A single insertion of the left son of the node's left subtree.
! [] (Http://blog.chinaunix.net/attachment/201108/14/25324849_1313308607C3xL.jpg)




On the left for the pre-adjustment node, we can see that the left and right sub-tree of K2 no longer satisfies the AVL equilibrium condition, adjusted for the picture.


As the K2 left child has become larger, so should reduce the height of K1, the K1 upward, and K2 corresponding also have to decline. K2 descended on the right sub-tree of K1 (since the K1 's left subtree was increased, so it is impossible to drop the K2 to the left K1 tree), y into K2 Zuozi (if y becomes K2 has a subtree, then K2 itself has no left subtree, but also down to the right subtree, then one minus one plus, left and wrong, balance factor into 2).


Case 2 (' LR '): An insert was made to the left child of the node
! [](.. /.. /pic/2676fca1-cf64-48b2-b4a7-73c41e8c16a7.png)


Starting from the first node to lose the balance of the analysis, B left for H,right for h+2, loss of balance, C upward, b down, so as to reduce the height of the whole tree (can be understood as the ' b,bl,c,cl,cr ' this tree, first put a ignore), C has been balanced, but a lost balance, C upward, a to descend, so as to reduce the whole tree (' C,a,ar '), CR connected to the left of a to prevent the right of a to become larger and lose balance, the final c,b,a have been balanced.


In fact, the method is consistent between them, the high node upward has lowered its height, the high downward lift, increase the height. Here the * * * height can be understood as the height of the tree * * *, they are using a strategy, which is a balance of the left and right sub-tree ' trend '


Case 3 (' RR '):


! [](.. /.. /pic/7109344f-642a-4ac0-9f89-9b576fb59578.png)




Case 4 (' RL ')


! [](.. /.. /pic/1cb097e6-d404-4cec-8442-1de3b3096a52.png)
Implementation code:


---
---


# B-Tree, B + Tree


---


---




Package Mainimport ("FMT") type DataType inttype Node avltreenodetype avltree *avltreenodetype avltreenode struct {key Da Tatypehigh intleft *avltreenoderight *avltreenode}func Main () {data: = []datatype{3, 2, 1, 4, 5, 6, 7, 16, 15, 14, 13, 1 2, one, ten, 8, 9}fmt. PRINTLN (data) var root avltree = Nilfor _, Value: = Range data {root = Avl_insert (root, Value) fmt. PRINTLN ("Root-key:", Root.key, "High:", Root.high, "left", Root.left, "right:", root.right)//Preorder (Root)} Preorder (Root) fmt. Println () Midorder (root) fmt. Println ()}func Hightree (p avltree) int {if p = = Nil {return-1} else {return P.high}}func max (A, b int) int {If a > B { Return a} else {return b}}/*please look Ll*/func left_left_rotation (k avltree) Avltree {var kl avltreekl = K.leftk.left = Kl.rightkl.right = Kk.high = Max (Hightree (K.left), Hightree (k.right)) + 1kl.high = max (Hightree (kl.left), K.high) + 1retur n kl}/*please look Rr*/func right_right_rotation (k avltree) Avltree {var kr avltreekr = K.rightk.right = kR.leftkr.left = Kk.high = Max (Hightree (K.left), Hightree (k.right)) + 1kr.high = max (K.high, Hightree (kr.right)) + 1return Kr}/*so easy*/func left_righ_rotation (k avltree) avltree {k.left = right_right_rotation (k.left) return Left_left_ Rotation (k)}func right_left_rotation (k avltree) avltree {k.right = left_left_rotation (k.right) return Right_right_ Rotation (k)}func Avl_insert (AVL avltree, key DataType) Avltree {if AVL = = Nil {AVL = new (Avltreenode) If AVL = nil {fmt. Println ("AVL tree Create error!") return Nil}else {avl.key = Keyavl.high = 0avl.left = Nilavl.right = nil}} else if key < Avl.key {Avl.left = Avl_insert ( Avl.left, key) if Hightree (avl.left)-hightree (avl.right) = = 2 {if key < Avl.left.key {//llavl = left_left_rotation (AVL) } else {//Lravl = Left_righ_rotation (AVL)}}} else if key > Avl.key {avl.right = Avl_insert (avl.right, key) if (hightre E (avl.right)-Hightree (avl.left)) = = 2 {if key < Avl.right.key {//Rlavl = Right_left_rotation (AVL)} else {fmt. Println ("Right rigHT ", key) AVL = Right_right_rotation (AVL)}}} else if key = = Avl.key {fmt. Println ("The Key", Key, "has existed!")} Notice:update High (May is this insert no rotation, so you should update high) Avl.high = Max (Hightree (avl.left), Hightre E (avl.right)) + 1return Avl}func preorder (AVL avltree) {if AVL! = nil {fmt. Print (Avl.key, "\ T") preorder (Avl.left) preorder (avl.right)}}func Midorder (AVL avltree) {if AVL! = Nil {Midorder ( Avl.left) fmt. Print (Avl.key, "\ T") Midorder (avl.right)}}/*display AVL tree*/func display (AVL avltree) {}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.