Created
November 9, 2013 00:34
-
-
Save wiredfool/7379882 to your computer and use it in GitHub Desktop.
print a binary tree of integers in level order. Level-order printing means printing each row of the tree from left to right, from root row to the deepest row. After each row, print a newline.
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
import Queue | |
class tr: | |
def __init__(self,val=None,children=None): | |
self.val=val | |
self.children=children or [] | |
def emit_level_order(tree): | |
cur_level = 0 | |
q = Queue.Queue() | |
q.put((0,tree)) | |
while True: | |
try: | |
(level, subt) = q.get_nowait() | |
except Queue.Empty: | |
break | |
if level > cur_level: | |
cur_level += 1 | |
print "%s " % subt.val, | |
for child in subt.children: | |
q.put_nowait((level+1, child)) | |
print "Binary" | |
emit_level_order(tr(3, [tr(9),tr(20,[tr(15),tr(7)])])) | |
print "K-ary" | |
emit_level_order(tr(3, [tr(9),tr(20,[tr(15),tr('k2'),tr(7)]), tr('knary')])) | |
$ python ./tree.py | |
Binary | |
3 | |
9 20 | |
15 7 | |
K-ary | |
3 | |
9 20 knary | |
15 k2 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment