Skip to content

Instantly share code, notes, and snippets.

@Kallin
Last active April 6, 2016 15:23
Show Gist options
  • Save Kallin/b5ab3f9a72050bc36b365ca1493f6579 to your computer and use it in GitHub Desktop.
Save Kallin/b5ab3f9a72050bc36b365ca1493f6579 to your computer and use it in GitHub Desktop.
def find_descendants(person)
descendants = []
stack = person[:children]
until stack.empty?
current_node = stack.pop
children = current_node[:children]
if children
children.each do |child|
stack.push child
end
end
descendants << current_node
end
descendants
end
person = {
name: 'Leo',
children: [
{name: 'Harvey', children: [
{name: 'Kallin'},
{name: 'Seth'}
]},
{name: 'Paul', children: [
{name: 'Mark'},
{name: 'Alan'}
]},
]
}
puts find_descendants(person)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment