Permalink
Browse files

refactor to use recursive to find the smallest successor

  • Loading branch information...
samnang committed Feb 22, 2011
1 parent 0d947ce commit 867386649cca4451a5afdaafdee43c1235588ef4
@@ -37,6 +37,10 @@ def find(value)
branch.find(value) if branch
end
+ def find_smallest_successor
+ left ? left.find_smallest_successor : self
+ end
+
def delete
case branches.count
when 0
@@ -68,19 +72,10 @@ def delete_when_one_child
end
def delete_when_two_children
- successor = find_smallest_successor
+ successor = right.find_smallest_successor
@value = successor.value
successor.parent.branches.delete(:left)
end
-
- def find_smallest_successor
- successor = right
- while successor.left
- successor = successor.left
- end
-
- successor
- end
end
end
@@ -37,6 +37,20 @@
end
end
+ describe "#find_smallest_successor" do
+ it "should return itself if no left child" do
+ tree << 5 << 6
+
+ tree.root.find_smallest_successor.should have_value 5
+ end
+
+ it "should return the smallest value" do
+ tree << 5 << 3 << 6 << 2
+
+ tree.root.find_smallest_successor.should have_value 2
+ end
+ end
+
describe "#delete" do
context "no child" do
it "should delete the node" do

0 comments on commit 8673866

Please sign in to comment.