题目描述:请实现两个函数,分别用来序列化和反序列化二叉树
思路:
序列化二叉树:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串。需要注意的是,序列化二叉树的过程中,如果遇到空节点,需要以某种符号(这里用#)表示。以下图二叉树为例,序列化二叉树时,需要将空节点也存入字符串中。
# -*- 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):
# write code here
list = s.split(',')
return self.deserializeTree(list)
def deserializeTree(self, list):
if len(list)<=0:
return None
val = list.pop(0)
root = None
if val != '#':
root = TreeNode(int(val))
root.left = self.deserializeTree(list)
root.right = self.deserializeTree(list)
return root