Skip to content

Instantly share code, notes, and snippets.

@itiut
Last active August 29, 2015 14:03
Show Gist options
  • Save itiut/d8295d14c5e8b92aca90 to your computer and use it in GitHub Desktop.
Save itiut/d8295d14c5e8b92aca90 to your computer and use it in GitHub Desktop.
Search for a node with a specific value
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