Skip to content

Instantly share code, notes, and snippets.

@ryf123
Created March 19, 2019 18:09
Show Gist options
  • Save ryf123/60b23d828a6338b394e1bac1c5b857e6 to your computer and use it in GitHub Desktop.
Save ryf123/60b23d828a6338b394e1bac1c5b857e6 to your computer and use it in GitHub Desktop.
import Queue
class AbNode(object):
def __init__(self, d):
self.data = d
self.children = []
def serial_bfs(node):
vals = []
q = Queue.Queue()
q.put(node)
vals.append(node.data)
while not q.empty():
nd = q.get(timeout=1)
for child in nd.children:
q.put(child)
vals.append(child.data)
vals.append('#')
return vals
def deserial_bfs(data):
q = Queue.Queue()
di = iter(data)
node = AbNode(di.next())
res = node
for val in di:
if val != '#':
child = AbNode(val)
node.children.append(child)
q.put(child)
elif not q.empty():
node = q.get(timeout=1)
return res
if __name__ == '__main__':
# 1 is the root
# 1's children: 2
# 2's children: 34
# 4's children: 56
# 6's children: 78
a = AbNode(1)
b = AbNode(2)
c = AbNode(3)
d = AbNode(4)
e = AbNode(5)
f = AbNode(6)
g = AbNode(7)
h = AbNode(8)
f.children = [g,h]
d.children = [e,f]
b.children = [c,d]
a.children = [b]
print serial_bfs(a)
print serial_bfs(deserial_bfs(serial_bfs(a)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment