diff options
| author | mo khan <mo@mokhan.ca> | 2013-08-30 17:36:46 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2013-08-30 17:36:46 -0600 |
| commit | e2bbfb897e073b5955088b1d71097cb0bfdb43f2 (patch) | |
| tree | 2b4693e7072bf22739ae5a32be99715b7593852b /lib/data_structures | |
| parent | e0626106c3b56615d4de2332aacd767a6af525d4 (diff) | |
balance avl tree with left right case
Diffstat (limited to 'lib/data_structures')
| -rw-r--r-- | lib/data_structures/avl_tree.rb | 34 |
1 files changed, 26 insertions, 8 deletions
diff --git a/lib/data_structures/avl_tree.rb b/lib/data_structures/avl_tree.rb index b2a2fce..3bfb1d1 100644 --- a/lib/data_structures/avl_tree.rb +++ b/lib/data_structures/avl_tree.rb @@ -54,7 +54,7 @@ class AVLTree end def re_balance - p balance_factor + p "balance factor for:#{data} is #{balance_factor}" if balance_factor < -1 p "right right case" @right.left = self @@ -62,22 +62,40 @@ class AVLTree @right = nil new_root elsif balance_factor > 1 - @left.right = self - new_root = @left - @left = nil - new_root + if @left.balance_factor == -1 + left_right_case + else + left_left_case + end else self end end - private - def balance_factor - p "left: #{left_height}, right: #{right_height}" + #p "left: #{left_height}, right: #{right_height}" (left_height - right_height) || 0 end + private + + def left_right_case + p "left right case" + left = @left + @left = @left.right + @left.left = left + left.right = nil + left_left_case + end + + def left_left_case + p "left left case" + @left.right = self + new_root = @left + @left = nil + new_root + end + def left_height @left ? @left.height : 0 end |
