Last active
December 23, 2015 14:19
-
-
Save jhamon/6648406 to your computer and use it in GitHub Desktop.
This file contains 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 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