class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Codec:
def serialize(self, root):
res, stack = [],[]
stack.append(root)
while stack:
if stack.count(None) == len(stack):
break
r = stack.pop(0)
if r:
stack.append(r.left)
stack.append(r.right)
res.append(r.val)
else:
res.append(r)
return str(res)
def deserialized(self, data):
import json
rstack = []
data = json.loads(data)
if data:
new = TreeNode(data.pop(0))
res = new
rstack.append(res)
while data:
r = rstack.pop(0)
if data:
d = data.pop(0)
if d:
r.left = TreeNode(d)
rstack.append(r.left)
if data:
d = data.pop(0)
if d:
r.right = TreeNode(d)
rstack.append(r.right)
return res
def createTree(self):
t = TreeNode(1)
t.left = TreeNode(2)
t.right = TreeNode(3)
t.right.left = TreeNode(4)
t.right.right = TreeNode(5)
return t
def pre(self, root):
if not root:
return
print(root.val)
self.pre(root.left)
self.pre(root.right)
c = Codec()
s = "[1,2,3,null,null,4,5,null,6,7,8]"
out=c.deserialized(s)
print(out)
#out = c.createTree()
s = c.serialize(out)
print(s)
c.pre(out)