449. Serialize and Deserialize BST——几乎所有树的面试题目都会回到BFS或者DFS,使用BFS,None节点存#

简介:

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

DFS

复制代码
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        if root is None:
            return "#"
        return str(root.val) + " " + self.serialize(root.left) + " " + self.serialize(root.right)

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        data = data.split()
        return self.deserialize_helper(data, [0])
        
    def deserialize_helper(self, data, i):
        if data[i[0]] == "#":
            return None
        root = TreeNode(int(data[i[0]]))
        i[0] += 1
        root.left = self.deserialize_helper(data, i)
        i[0] += 1
        root.right = self.deserialize_helper(data, i)
        return root
                
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
复制代码

 DFS 2:

复制代码
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        if root is None:
            return "#"
        return str(root.val) + " " + self.serialize(root.left) + " " + self.serialize(root.right)

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        data = data.split()
        if data[0] == '#':
            return None
        node = root = TreeNode(int(data[0]))
        stack = [root]
        i = 1
        while data[i] != '#':
            node.left = TreeNode(int(data[i]))
            stack.append(node.left)
            node = node.left
            i += 1
        while stack:
            node = stack.pop()
            i += 1
            if data[i] != '#': 
                node.right = TreeNode(int(data[i]))
                stack.append(node.right)
                node = node.right
                i += 1
                while data[i] != '#':
                    node.left = TreeNode(int(data[i]))
                    stack.append(node.left)
                    node = node.left
                    i += 1
            else:
                node.right = None
        return root
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
复制代码

 

BFS

复制代码
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        if root is None:
            return ""
        stack = [root]
        ans = str(root.val)
        while stack:
            stack2 = []
            for node in stack:
                if node.left:
                    stack2.append(node.left)
                    ans += " "+str(node.left.val)
                else:
                    ans += " #"
                if node.right:
                    stack2.append(node.right)
                    ans += " " + str(node.right.val)
                else:
                    ans += " #"
            stack = stack2
        return ans
        

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        array = data.split()
        if not array:
            return None
        root = TreeNode(int(array[0]))
        stack = [root]
        i = 1
        while stack:
            stack2 = []
            for node in stack:
                if array[i] != '#': 
                    node.left = TreeNode(int(array[i]))
                    stack2.append(node.left)
                else:
                    node.left = None
                i += 1
                if array[i] != '#': 
                    node.right = TreeNode(int(array[i]))
                    stack2.append(node.right)
                else:
                    node.right = None                
                i += 1
            stack = stack2
        return root
                
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
复制代码













本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/6242763.html ,如需转载请自行联系原作者

相关文章
|
3月前
|
存储 前端开发 JavaScript
【面试题】Promise只会概念远远不够,还需这17道题目巩固!
【面试题】Promise只会概念远远不够,还需这17道题目巩固!
LeetCode | 面试题 02.02. 返回倒数第 k 个节点
LeetCode | 面试题 02.02. 返回倒数第 k 个节点
|
1月前
|
JavaScript 前端开发 API
vue面试题目汇总
vue面试题目汇总
33 4
|
1月前
|
算法 Linux 调度
嵌入式linux面试题目总结
嵌入式linux面试题目总结
33 0
|
2月前
|
安全 Java 编译器
Go语言面试宝典:50道必会题目与精解
本文提供了50道覆盖Go语言核心概念、并发编程、内存管理、包管理、错误处理和测试等方面的面试题及其详细答案,旨在帮助开发者全面准备Go语言技术面试。
|
2月前
|
Linux
面试题12: 基本Linux 命令题目
面试题12: 基本Linux 命令题目
|
3月前
|
存储 JavaScript 安全
Vue基础面试题题目一
Vue基础面试题题目一
26 0
|
3月前
|
存储 算法 Java
盛算信息-面试经历-笔试部分-完整题目(一)
盛算信息-面试经历-笔试部分-完整题目(一)
32 2
|
3月前
|
算法
面试题 02.03:删除中间节点
面试题 02.03:删除中间节点
13 0
|
3月前
|
算法
面试题 02.02:返回倒数第 k 个节点
面试题 02.02:返回倒数第 k 个节点
18 0