题解 | #序列化二叉树#

序列化二叉树

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def __init__(self) -> None:
        self.index = 0
        self.s = ''

    def func1(self, root):
        if  not root:
            self.s += '#'
            return 
        self.s += str(root.val) + '!'  
        self.func1(root.left)
        self.func1(root.right)

    def Serialize(self, root):
        self.s = ''
        if not root:
            return '#'
        self.func1(root)
        return self.s 

    def func2(self, s):
        if self.index >= len(s) or s[self.index] == '#':
            self.index += 1
            return None

        num = 0
        while s[self.index] != '!' or self.index >= len(s):
            num = num*10 + int(s[self.index])
            self.index += 1
        node = TreeNode(num)
        if self.index == len(s):
            return node
        else:
            self.index += 1
        node.left = self.func2(s)
        node.right = self.func2(s)
        return node
            
    def Deserialize(self, s):
        if s == '#':
            return None
        return self.func2(s)






全部评论

相关推荐

totoroyyw:千年老妖😂
投递华为等公司10个岗位
点赞 评论 收藏
分享
10-30 10:16
南京大学 Java
龚至诚:给南大✌️跪了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务