180 likes | 382 Views
5. 3. 7. 1. 2. 8. AVL Trees. Binary Search Tree. Binary search tree, using simple insert and delete procedures the tree is nearly balance add - fast O(log n) delete a target - fast O(log n) search - fast O(log n)
E N D
5 3 7 1 2 8 AVL Trees
Binary Search Tree • Binary search tree, using simple insert and delete procedures • the tree is nearly balance • add - fastO(log n) • delete a target - fastO(log n) • search - fastO(log n) • the tree is highly unbalance, it becomes a singly linked list (the worst case) • add, delete and search - slowO(n)effectively using sequential search to find a location
AVL Tree (Adelson-Velskii & Landis) • AVL Tree are BST with an additional balance condition to ensure the depth of the tree is O(log2N) • Balance Condition: for any node in the tree, the height (the length of the path form the node to the deepest leaf) of the left and right subtrees can differ by at most 1. • Must ensure that after insertion and deletion of a node, the balance condition is preserved
Adding/deleteing node from AVL Tree * Add a node connected to some node? * Delete some node? • After an insertion, the nodes on the path from the insertion point to the root can have their balances altered. • Rotationrestores local balance
Single rotation (When the problem happens in “A”) k2 k1 k1 C k2 A A B B C
Single rotation Single rotation (When the problem happens in “C”) k2 k1 k1 A k2 C B C A B
3 3 1 5 1 7 2 4 7 5 9 2 6 9 4 6 8 8 Single Rotation
Single rotation k2 Perform Single Rotation on K2 Node *k1 = K2 -> left; //identify k1 K2 -> left = K1 -> Right K1 -> right = K2 K2 = K1 k1 k1 C k2 A A B B C
Single rotation • Example: in BST, if we insert 1, 2, 3, 4, 5, 6 in order, we get a BST tree like:
Single rotation • In AVL tree, it would be:
Single rotation • In AVL tree, it would be:
Single Rotation Doesn’t Work in Some Cases • However, when the problem happens in “B”…
Single Rotation Doesn’t Work in Some Cases k2 k2 k1 C k1 C A B A B
Single Rotation Doesn’t Work in Some Cases k2 k2 k1 k1 A A B C C B
3 3 1 5 1 8 2 4 8 5 9 2 6 9 4 6 7 7 Single Rotation Doesn’t Work in Some Cases
3 3 1 5 1 6 2 4 8 5 8 2 6 9 4 7 9 7 x z A y x y z D B C A B C D Double Rotation
Try • Insert 1, 2, 3, 4, 5, 3.5
x A y z D B C Double Rotation • Perform Double rotation on X = Perform Single Rotation on Y + Perform Single Rotation on X