欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python:序列化二叉树

程序员文章站 2022-08-31 19:19:42
Python:序列化二叉树。 题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 class TreeNode: def __init__(self, x...

Python:序列化二叉树。

题目描述

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

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def Serialize(self, root):
        # write code here
        tree, ch = [root], []
        while len(tree) > 0:
            temp = tree.pop(0)
            if temp is None:
                ch.append('#*')
            else:
                ch.append(str(temp.val) + '*')
                tree.append(temp.left)
                tree.append(temp.right)
        return ''.join(ch)

    def Deserialize(self, s):
        # write code here
        s1, i = s.split('*'), 0
        if s1[i] == '#':
            return None
        root = TreeNode(int(s1[i]))
        tree = [root]
        while len(tree) > 0:
            te = tree.pop(0)
            i += 1
            if s1[i] != '#':
                k = TreeNode(int(s1[i]))
                te.left = k
                tree.append(k)
            i += 1
            if s1[i] != '#':
                k = TreeNode(int(s1[i]))
                te.right = k
                tree.append(k)
        return root