题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
思路:序列化,将二叉树变成字符串并且节点的val用",“隔开,用先序,空节点用”#"
反序列化,将字符串s,去掉","后还原成二叉树
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Serialize(self, root): # 序列化指返回字符串,空节点为"#"
if not root:
return "#"
return str(root.val) + "," + self.Serialize(root.left) + "," + self.Serialize(root.right) # 先序,序列化用","来分割
def Deserialize(self, s): # s为字符串,反序列化指把字符串还原成二叉树
root, index = self.deserialize(s.split(","), 0)
return root
def deserialize(self, s, index): # s为列表,转换成列表因为后面要用int,而str不可变,list可变
if s[index] == "#":
return None, index + 1
root = TreeNode(int(s[index]))
index += 1
root.left, index = self.deserialize(s, index) # 是list s不是一个元素s[index]
root.right, index = self.deserialize(s, index) # root.left和root.right 的index不同,例:进入root.left的index为1,返回index为3,则进入root.right的index为3
return root, index