题解 | #序列化二叉树#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def seRec(self, root, eles):
return
def Serialize(self, root):
# write cod
que = []
cur = root
ret = []
if cur:
que.append(cur)
ret.append(str(cur.val))
while len(que) > 0:
curQue = []
for item in que:
if item.left:
curQue.append(item.left)
ret.append(str(item.left.val))
else:
ret.append("#")
if item.right:
curQue.append(item.right)
ret.append(str(item.right.val))
else:
ret.append("#")
que = curQue
ret = ",".join(ret)
print(ret)
return ret
def Deserialize(self, s):
# write code here
def getNode(ch):
if ch == "#":
return None
else:
return TreeNode(int(ch))
print(s)
s = s.split(",")
if len(s) <= 0:
return None
if s[0] == "":
return None
root = None
curQueue = []
nextQueue = []
idx = 0
retNode = getNode(s[idx])
if retNode != None:
root = retNode
else:
return root
curQueue.append(root)
print(s)
while len(curQueue) > 0:
nextQueue = []
for item in curQueue:
leftNode = getNode(s[idx+1])
rightNode = getNode(s[idx+2])
if leftNode:
nextQueue.append(leftNode)
item.left = leftNode
if rightNode:
nextQueue.append(rightNode)
item.right = rightNode
idx += 2
curQueue = nextQueue
return root
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def seRec(self, root, eles):
return
def Serialize(self, root):
# write cod
que = []
cur = root
ret = []
if cur:
que.append(cur)
ret.append(str(cur.val))
while len(que) > 0:
curQue = []
for item in que:
if item.left:
curQue.append(item.left)
ret.append(str(item.left.val))
else:
ret.append("#")
if item.right:
curQue.append(item.right)
ret.append(str(item.right.val))
else:
ret.append("#")
que = curQue
ret = ",".join(ret)
print(ret)
return ret
def Deserialize(self, s):
# write code here
def getNode(ch):
if ch == "#":
return None
else:
return TreeNode(int(ch))
print(s)
s = s.split(",")
if len(s) <= 0:
return None
if s[0] == "":
return None
root = None
curQueue = []
nextQueue = []
idx = 0
retNode = getNode(s[idx])
if retNode != None:
root = retNode
else:
return root
curQueue.append(root)
print(s)
while len(curQueue) > 0:
nextQueue = []
for item in curQueue:
leftNode = getNode(s[idx+1])
rightNode = getNode(s[idx+2])
if leftNode:
nextQueue.append(leftNode)
item.left = leftNode
if rightNode:
nextQueue.append(rightNode)
item.right = rightNode
idx += 2
curQueue = nextQueue
return root