Commit 5a10d41

mo khan <mo@mokhan.ca>
2013-09-01 16:23:32
implement right left rotation in avl tree.
1 parent e2bbfb8
Changed files (2)
lib
data_structures
spec
data_structures
lib/data_structures/avl_tree.rb
@@ -56,11 +56,11 @@ class AVLTree
     def re_balance
       p "balance factor for:#{data} is #{balance_factor}"
       if balance_factor < -1
-        p "right right case"
-        @right.left = self
-        new_root = @right
-        @right = nil
-        new_root
+        if @right.balance_factor == 1
+          right_left_case
+        else
+          right_right_case
+        end
       elsif balance_factor > 1
         if @left.balance_factor == -1
           left_right_case
@@ -73,12 +73,28 @@ class AVLTree
     end
 
     def balance_factor
-      #p "left: #{left_height}, right: #{right_height}"
       (left_height - right_height) || 0
     end
 
     private
 
+    def right_left_case
+      p "right left case"
+      right = @right
+      @right = right.left
+      @right.right = right
+      right.left = nil
+      right_right_case
+    end
+
+    def right_right_case
+      p "right right case"
+      @right.left = self
+      new_root = @right
+      @right = nil
+      new_root
+    end
+
     def left_right_case
       p "left right case"
       left = @left
spec/data_structures/avl_tree_spec.rb
@@ -129,5 +129,29 @@ describe AVLTree do
         sut.root.right.data.should == 5
       end
     end
+
+    context "with a right-left case" do
+      before :each do
+        sut.add(3)
+        sut.add(5)
+        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