Professional Documents
Culture Documents
AVL Trees
For some binary search tree, the height could be quite large, which is not good for searching. An AVL tree is a binary search tree with a balance condition
To
ensure that the height of the tree is O(logN) For every node in the AVL tree, the height of left subtree and the height of the right subtree can differ by at most one.
AVL Trees
The height of the left subtree minus the height of the right subtree of a node is called the balance of the node. For an AVL tree, the balances of the nodes are always -1, 0 or 1.
The
Given an AVL tree, if insertions or deletions are performed, the AVL tree may not remain height balanced.
AVL Trees
5 2 8 2 7 8
An AVL Tree
AVL Trees
To maintain the height balanced property of the AVL tree after insertion or deletion, it is necessary to perform a transformation on the tree so that (1) the inorder traversal of the transformed tree is the same as for the original tree (i.e., the new tree remains a binary search tree). (2) the tree after transformation is height balanced.
AVL Trees
After an insertion, only nodes that are on the path from the insertion point to the root might have their balance altered Follow the path up to the root, find the first node (i.e., deepest) whose new balance violates the AVL condition. Call this node a. Rebalance the tree at node a. This guarantees that the entire tree is balanced.
AVL Trees
Violation
1. left subtree of left child of a (LL case) 2. right subtree of left child of a (LR case) 3. left subtree of right child of a (RL case) 4. right subtree of right child of a (RR case)
AVL Trees
Rotation
- double rotation
For
i.e. LL case
Insert 6
Insert 7
Example:
Insert 14
Insert 12
Inserting 9