o
class TreeNode:
def __init__(self, val):
self.val = val
self.children = []
def serialize(root):
def helper(root, ret):
ret.append(str(root.val))
for child in root.children:
helper(child, ret)
ret.append('#')
ret = []
if not root: return ""
helper(root, ret)
return ','.join(ret)
def deserialize(s):
def helper(s, idx):
start = idx
while idx<len(s) and s[idx]!=',':
idx+=1
c = s[start:idx]
idx+=1
if c=='#':
return None, idx
root = TreeNode(int(c))
child, idx = helper(s, idx)
while child is not None:
root.children.append(child)
child, idx = helper(s, idx)
return root, idx
root, i = helper(s, 0)
return root
print serialize(deserialize("1,2,3,#,4,5,#,#,#,6,#,7,8,#,9,#,10,#,11,#,#,#"))