剑指offer序列化与反序列化,VSCode和平台结果不同
大佬们,剑指offer序列化与反序列化那道题我是这么做的:
class Solution:
def Serialize(self, root):
# write code here
if not root:
return ""
self.number = []
self.cur = []
self.number.append(root)
self.Se(root)
#print(self.cur)
return ",".join(self.cur)
def Se(self,root):
while(self.number):
if self.number[0] != "#" and self.number[0]:
self.cur.append(str(self.number[0].val))#AttributeError: 'NoneType' object has no attribute 'val',number[0]==None
if self.number[0].left:
self.number.append(self.number[0].left)
if self.number[0].right:
self.number.append(self.number[0].right)#没有判断语句,一直循环,self.number[None]
self.number.pop(0)
if len(self.number)>0 and self.number[0]=="#":
self.cur.append("#")#IndexError: list index out of range
self.number.pop(0)
#if not self.number[0]:
def Deserialize(self, s):
# write code here
if not s:
return
l = s.split(",")
root = TreeNode(None)
return(self.listCreatTree(root,l,0))
def listCreatTree(self, root,l,i):
if i < len(l):
val = l[i]
if val != "#":
root = TreeNode(val)
root.left = self.listCreatTree(root, l, 2*i+1)
root.right = self.listCreatTree(root, l, 2*i+2)
return root
if val == "#":
root = TreeNode(val)
return root
求大佬告知(有答案,自己觉得思路这样走想多一种思路)
#Python#