lab19: impl
This commit is contained in:
@@ -5,6 +5,28 @@ class Tree
|
||||
@left = left
|
||||
@right = right
|
||||
end
|
||||
|
||||
def each_node(&block)
|
||||
block.call(@value)
|
||||
@left.each_node(&block) if @left
|
||||
@right.each_node(&block) if @right
|
||||
end
|
||||
|
||||
def method_missing(method_name, *args)
|
||||
method_name = method_name.to_s
|
||||
path = method_name.scan(/(left|right)/).flatten
|
||||
current_node = self
|
||||
path.each do |direction|
|
||||
if direction == "left"
|
||||
current_node = current_node.left
|
||||
elsif direction == "right"
|
||||
current_node = current_node.right
|
||||
end
|
||||
return nil if current_node.nil?
|
||||
end
|
||||
return current_node.value
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
my_tree = Tree.new(42,
|
||||
@@ -32,4 +54,3 @@ p my_tree.left_left
|
||||
p my_tree.right_left
|
||||
p my_tree.left_left_right
|
||||
p my_tree.left_left_left_right
|
||||
|
||||
|
||||
Reference in New Issue
Block a user