Commit e2bbfb8

mo khan <mo@mokhan.ca>
2013-08-30 23:36:46
balance avl tree with left right case
1 parent e062610
Changed files (2)
lib
data_structures
spec
data_structures
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
spec/data_structures/avl_tree_spec.rb
@@ -106,5 +106,28 @@ describe AVLTree do
       end
     end
 
+    context "with a left-right case" do
+      before :each do
+        sut.add(5)
+        sut.add(3)
+        sut.add(4)
+      end
+
+      it "should adjust the height" do
+        sut.height.should == 2
+      end
+
+      it "should have a new root" do
+        sut.root.data.should == 4
+      end
+
+      it "should have a proper left side" do
+        sut.root.left.data.should == 3
+      end
+
+      it "should have a proper right side" do
+        sut.root.right.data.should == 5
+      end
+    end
   end
 end