Skip to content

Instantly share code, notes, and snippets.

@jadon1979
Created June 10, 2014 22:32
Show Gist options
  • Select an option

  • Save jadon1979/a7a3460165547be35ccd to your computer and use it in GitHub Desktop.

Select an option

Save jadon1979/a7a3460165547be35ccd to your computer and use it in GitHub Desktop.
=begin
a
/ \
b c
/ / \
d e f
tree = ['a', ['b', 'd' ], ['c', 'e', 'f']]
print_tree(tree)
=>
a
b c
d e f
Queue tree root and line break, shift first element, check for
left and/or right branches and, if found, then queue up
individual branches
=end
def print_tree(tree)
[tree, "\n"].tap do |q|
while q.any?
n = q.shift
unless n == "\n"
print "%s " % n[0]
2.times do |i|
branch = n.fetch(i+1, nil)
q << branch unless branch.nil?
end if n.class == Array
else
puts n
q << n unless q.empty?
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment