zoukankan      html  css  js  c++  java
  • LeeCode 449. 序列化和反序列化二叉搜索树

    449. 序列化和反序列化二叉搜索树

    Difficulty: 中等

    序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。

    设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。

    编码的字符串应尽可能紧凑。

    示例 1:

    输入:root = [2,1,3]
    输出:[2,1,3]
    

    示例 2:

    输入:root = []
    输出:[]
    

    提示:

    • 树中节点数范围是 [0, 10<sup>4</sup>]
    • 0 <= Node.val <= 10<sup>4</sup>
    • 题目数据 保证 输入的树是一棵二叉搜索树。

    注意:不要使用类成员/全局/静态变量来存储状态。 你的序列化和反序列化算法应该是无状态的。

    Solution

    既然给定了二叉搜索树,那就要充分利用二叉搜索树的性质:二叉搜索树中任意节点值大于其左子节点,小于其右子节点,通过先序遍历取出二叉搜索树中的所有结点,并将取出的结点转成字符串,完成序列化。

    对于反序列化,由序列化过程得到的结果(DLR),可以确定根节点D左右两边的结点,然后可以通过递归的方式完成反序列化。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Codec:
    
        def serialize(self, root: TreeNode) -> str:
            """Encodes a tree to a single string.
            """
            if not root: 
                return ''
            stack, res = [root], []
            while stack:
                root = stack.pop()
                res.append(str(root.val))
                if root.right:
                    stack.append(root.right)
                if root.left:
                    stack.append(root.left)
            return ','.join(res)
            
    
        def deserialize(self, data: str) -> TreeNode:
            """Decodes your encoded data to tree.
            """
            if not data: 
                return None
            
            queue = []
            for e in data.split(','):
                if e != '':
                    queue.append(int(e))
            return self.helper(queue)
        
        def helper(self, queue):
            if not queue: 
                return None
            root = queue.pop(0)
            smallerQueue = []
            while queue and queue[0] < root:
                smallerQueue.append(queue.pop(0))
            
            root = TreeNode(root)
            root.left = self.helper(smallerQueue)
            root.right = self.helper(queue)
            return root
            
    
    # Your Codec object will be instantiated and called as such:
    # Your Codec object will be instantiated and called as such:
    # ser = Codec()
    # deser = Codec()
    # tree = ser.serialize(root)
    # ans = deser.deserialize(tree)
    # return ans
    
  • 相关阅读:
    Linux 修改最大线程数
    Openresty+Nginx+Lua+Nginx_http_upstream_check_module 搭建
    SSDB 性能测试
    面向对象:类的成员
    封装,多态,类的约束,super()深入了解
    面向对象:继承
    面向对象:类的空间问题,类之间关系
    面向对象初识
    软件开发规范
    模块(四)包和logging日志
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14111672.html
Copyright © 2011-2022 走看看