Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

refactor to use recursive to find the smallest successor

  • Loading branch information...
commit 867386649cca4451a5afdaafdee43c1235588ef4 1 parent 0d947ce
@samnang authored
View
15 binary_search_tree/lib/binary_search_tree/node.rb
@@ -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
View
14 binary_search_tree/spec/binary_search_tree_spec.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.