Skip to content

Instantly share code, notes, and snippets.

@jhamon
Last active December 23, 2015 14:19
Show Gist options
  • Save jhamon/6648406 to your computer and use it in GitHub Desktop.
Save jhamon/6648406 to your computer and use it in GitHub Desktop.
class TreeNode
# ...
def dfs(target_value = nil, &blk)
# Depth-first search. Returns TreeNode instance
# with target value, or nil if not in tree.
# Optionally accepts a block and returns the
# first node encounted for which the block
# evaluates to true. This allows us to dfs
# search using arbitrary criteria.
if block_given? && !target_value.nil?
raise ArgumentError, "takes either a block or a target value"
end
return self if @value == target_value
return self if !blk.nil? && blk.call(@value)
found_node = nil
@children.each do |child|
found_node = child.dfs(target_value, &blk)
return found_node unless found_node.nil?
end
return found_node
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment