Last active
August 29, 2015 14:03
-
-
Save itiut/d8295d14c5e8b92aca90 to your computer and use it in GitHub Desktop.
Search for a node with a specific value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tree | |
attr_accessor :root | |
def search_for_node(value) | |
@root.search_self_and_children value | |
end | |
end | |
class Node | |
attr_accessor :value, :children | |
def initialize(value) | |
@value = value | |
@children = [] | |
end | |
def search_self_and_children(value) | |
return self if @value == value | |
@children.each do |child| | |
result_node = child.search_self_and_children value | |
return result_node if result_node | |
end | |
nil | |
end | |
end | |
# generate tree | |
tree = Tree.new | |
# add nodes to tree | |
# ... | |
# search for a node with a specific value | |
result_node = tree.search_for_node(:some_value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment