Last active
December 28, 2015 07:09
-
-
Save mpenkov/7461857 to your computer and use it in GitHub Desktop.
Coding for Interview: Level Order Tree Print
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
def bfs(root): | |
nodes = [(0,root)] | |
prev_level = 0 | |
while nodes: | |
level, node = nodes.pop(0) | |
if level > prev_level: | |
print node.value, | |
prev_level = level | |
for c in node.children: | |
nodes.append((level+1, c)) | |
class Node: | |
def __init__(self, value, children=None): | |
self.value = value | |
self.children = children if children else [] | |
if __name__ == "__main__": | |
root = Node(3, [Node(9), Node(20, [Node(15), Node(17)])]) | |
bfs(root) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment