Guest User

Untitled

a guest
Jul 19th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. /**
  2. * Balance the tree, takes O(n) time
  3. */
  4. template <class T, typename Compare, typename Distance>
  5. void AvlTree<T,Compare, Distance>::balanceTree(AvlNode<T,Compare, Distance>* &node)
  6. {
  7. if ( node )
  8. {
  9. // First see what the balance factor for this node is
  10. //
  11. int balFactor = node->balanceFactor();
  12.  
  13. if ( balFactor < -1 )
  14. {
  15. // See if we're heavy left of the left
  16. //
  17. if( node->left->balanceFactor() < 0 )
  18. {
  19. rotateWithLeftChild( node );
  20. }
  21. else // if (node->left->balanceFactor() > 0 )
  22. {
  23. // We're heavy on the right of the left
  24. //
  25. doubleWithLeftChild( node );
  26. }
  27. }
  28. else if ( balFactor > 1 )
  29. {
  30. // See if it we're heavy right of the right
  31. //
  32. if( node->right->balanceFactor() > 0 )
  33. {
  34. rotateWithRightChild( node );
  35. }
  36. else // if ( node->right->balanceFactor() < 0 )
  37. {
  38. // The element goes on the left of the right
  39. //
  40. doubleWithRightChild( node );
  41. }
  42. }
  43. else // if ( balFactor >= -1 && balFactor <= 1)
  44. {
  45. // We're balanced here, but are our children balanced?
  46. //
  47. balanceTree(node->left);
  48. balanceTree(node->right);
  49. }
  50. }
  51. }
Add Comment
Please, Sign In to add comment