在VSCode平台上全代码:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
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
'''
flag=-1
def Serialize(self, root):
# write code here
if not root:
return '#'
return str(root.val)+','+self.Serialize(root.left)+','+self.Serialize(root.right)
def Deserialize(self, s):
# write code here
#print(s)
self.flag+=1
lis=s.split(',')
if self.flag>=len(lis):
return None
root=None
#print("----------",self.flag,len(lis),len(s))
if lis[self.flag]!='#':
root=TreeNode(int(lis[self.flag]))
root.left=self.Deserialize(s)
root.right=self.Deserialize(s)
return root
'''
def midTraversal(self, root):
if root:
self.midTraversal(root.left)
print(root.val)
self.midTraversal(root.right)
if __name__ == "__main__":
#b = [8,6,10,5,7,9,11]
#print()
#print(list(b))
#print(b.split(","))
a = Solution()
root = TreeNode(None)
root = a.Deserialize("8,6,10,5,7,9,11")
print("+++++")
a.midTraversal(root)
print("--------------------")
print(a.Serialize(root))