Created
June 10, 2014 22:32
-
-
Save jadon1979/a7a3460165547be35ccd 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
| =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