huashiyilvqi
BAN USERsorry I submitted twice
- huashiyilvqi August 03, 2015My python solution with test. Uncomment print statement to see output.
class Node:
def __init__(self, val):
self.val = val
self.sons = []
class Solution:
def __init__(self, root):
self.sequence = str(root.val)
cur = [root]
while cur:
next = []
for i in cur:
self.sequence += str(len(i.sons))
for ii in i.sons:
next.append(ii)
self.sequence += str(ii.val)
cur = next
def de_serial(self):
strs = self.sequence
# print strs
idx = 1
cur = [Node(int(strs[0]))]
root = cur[0]
while idx < len(strs):
next = []
for i in cur:
num = int(strs[idx])
# print 'num', num
idx += 1
for j in range(num):
tmp = Node(int(strs[idx]))
# print tmp.val
i.sons.append(tmp)
next.append(tmp)
idx += 1
cur = next
# print map(lambda x: x.val, next)
return root
if __name__ == "__main__":
tree = Node(1)
two = Node(2)
three = Node(3)
four = Node(4)
five = Node(5)
six = Node(6)
seven = Node(7)
tree.sons = [two, three, four]
two.sons = [five]
three.sons = [six, seven]
a = Solution(tree)
print a.de_serial()
Isn't it short?
- huashiyilvqi August 03, 2015