Last active
September 17, 2015 19:16
-
-
Save vincentchin/a7d53a7a80b15cd96059 to your computer and use it in GitHub Desktop.
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
# In the above example it will check to see if the payload is 11 in the following order: 2, 7, 6, 5 when | |
# it gets to 5 and 5 has no children, it will return to the 6 and go to any children 6 has. 6 has a | |
# remaining child, which is 11 so that node is checked and since that value is the correct value it | |
# will be returned and searching will stop. | |
class Tree | |
attr_accessor :payload, :children | |
def initialize(payload, children) | |
@payload = payload | |
@children = children | |
end | |
end | |
# The "Leafs" of a tree, elements that have no children | |
fifth_node = Tree.new(5, []) | |
eleventh_node = Tree.new(11, []) | |
fourth_node = Tree.new(4, []) | |
# The "Branches" of the tree | |
ninth_node = Tree.new(9, [fourth_node]) | |
sixth_node = Tree.new(6, [fifth_node, eleventh_node]) | |
seventh_node = Tree.new(7, [sixth_node]) | |
fifth_node = Tree.new(5, [ninth_node]) | |
# The "Trunk" of the tree | |
trunk = Tree.new(2, [seventh_node, fifth_node]) | |
def depth_first_search(value,node) | |
@current_node = node | |
if @current_node.payload == value | |
puts "Destination Node #{@current_node.payload}" | |
return @current_node | |
else | |
puts "Go to next Node #{@current_node.payload}" | |
if @current_node.children != nil | |
@current_node.children.each do |x| | |
depth_first_search(value, x) | |
end | |
end | |
end | |
end | |
depth_first_search(11, trunk) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment