剑指offer 面试题37 python版+解析:序列化的二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mabozi08/article/details/88855168

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树

思路:采用递归的思想。直接用前序遍历的递归就可以序列化二叉树。反序列化就是找到根节点,然后构建左子树,然后右子树

# -*- coding:utf-8 -*-
# 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 "$"
        return str(root.val)+","+self.Serialize(root.left)+","+self.Serialize(root.right)
    def Deserialize(self, s):
        # write code here
        root, index = self.deserialize(s.split(","), 0)
        return root
    def deserialize(self, s, index):
        if s[index] == "$":
            return None, index+1
        root = TreeNode(int(s[index]))
        index+=1
        root.left, index = self.deserialize(s, index)
        root.right, index = self.deserialize(s, index)
        return root,index
        

猜你喜欢

转载自blog.csdn.net/mabozi08/article/details/88855168