12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

454 Chap. 13 Advanced Tree <strong>Structures</strong>3737244224427324042732404221202120Figure 13.4 Example of an insert operation that violates the AVL tree balanceproperty. Prior <strong>to</strong> the insert operation, all nodes of the tree are balanced (i.e., thedepths of the left <strong>and</strong> right subtrees for every node differ by at most one). Afterinserting the node with value 5, the nodes with values 7 <strong>and</strong> 24 are no longerbalanced.5SXXCASAB B C(a)(b)Figure 13.5 A single rotation in an AVL tree. This operation occurs when theexcess node (in subtree A) is in the left child of the left child of the unbalancednode labeled S. By rearranging the nodes as shown, we preserve the BST property,as well as re-balance the tree <strong>to</strong> preserve the AVL tree balance property. The casewhere the excess node is in the right child of the right child of the unbalancednode is h<strong>and</strong>led in the same way.Our problem now is how <strong>to</strong> balance the tree in O(log n) time. It turns out thatwe can do this using a series of local operations known as rotations. Cases 1 <strong>and</strong>4 can be fixed using a single rotation, as shown in Figure 13.5. Cases 2 <strong>and</strong> 3 canbe fixed using a double rotation, as shown in Figure 13.6.The AVL tree insert algorithm begins with a normal BST insert. Then as the recursionunwinds up the tree, we perform the appropriate rotation on any node that is

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!