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, []) def deserialize_helper(self, data, i):
if data[i[]] == "#":
return None
root = TreeNode(int(data[i[]]))
i[] +=
root.left = self.deserialize_helper(data, i)
i[] +=
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[]))
stack = [root]
i =
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 +=
if array[i] != '#':
node.right = TreeNode(int(array[i]))
stack2.append(node.right)
else:
node.right = None
i +=
stack = stack2
return root # Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))

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

  1. 【LeetCode】449. Serialize and Deserialize BST 解题报告(Python)

    [LeetCode]449. Serialize and Deserialize BST 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/pro ...

  2. [leetcode]449. Serialize and Deserialize BST序列化与反序列化BST

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  3. [leetcode]449. Serialize and Deserialize BST序列化反序列化二叉搜索树(尽量紧凑)

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  4. 449. Serialize and Deserialize BST

    https://leetcode.com/problems/serialize-and-deserialize-bst/#/description Serialization is the proce ...

  5. LeetCode 449. Serialize and Deserialize BST

    原题链接在这里:https://leetcode.com/problems/serialize-and-deserialize-bst/description/ 题目: Serialization i ...

  6. 【leetcode】449. Serialize and Deserialize BST

    题目如下: Serialization is the process of converting a data structure or object into a sequence of bits ...

  7. [leetcode]449. Serialize and Deserialize BST设计BST的编解码

    这道题学到了东西. /* 一开始想着中序遍历,但是解码的时候才发现,中序遍历并不能唯一得确定二叉树. 后来看了网上的答案,发现先序遍历是可以的,观察了一下,对于BST,先序遍历确实是可以 唯一得确定. ...

  8. 449 Serialize and Deserialize BST 序列化和反序列化二叉搜索树

    详见:https://leetcode.com/problems/serialize-and-deserialize-bst/description/ C++: /** * Definition fo ...

  9. [LeetCode] Serialize and Deserialize BST 二叉搜索树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

随机推荐

  1. html中出现的script失效

    如果在Controller中出现script代码类似 $hello_str='Hello God<script>alert(3);</script>'; 那么我不希望在传给vi ...

  2. OC拓展(category)

    1. 扩展类的功能Category提供了一种比继承(inheritance)更为简洁的方法来对class进行扩展,我们可以为任何已经存在的class添加方法(不包括数据成员)却不需要访问该class的 ...

  3. nodejs学习笔记<六>文件处理

    nodejs处理文件模块:fs  —>  var fs = require(‘fs’); 读取文件:readFileSync & readFile 读取文件路径为绝对: 读取结果需要to ...

  4. oracle的正则表达式

    阅读目录 1.oracle(regular expression)简单介绍 2.oracle正则特殊字符 3.oracle正则字符簇 4.各种操作符的运算优先级 5.模拟测试例子 6.oracle对应 ...

  5. Docker-网络基础配置

    从外部访问容器 指定容器端口随机映射主机端口 [root@wls12c /]$ docker run -p -d --name web tomcat /bin/bash -c /root/apache ...

  6. Erlang安装笔记

    今天,为了安装RabbitMQ,需要安装Erlang,中间遇到了一些坑,记录下来. 1. 下载Erlang安装包 http://www.erlang.org/downloads http://erla ...

  7. iOS开发之 Xcode 6 创建一个Empty Application

    参考链接http://jingyan.baidu.com/article/2a138328bd73f2074b134f6d.html Xcode 6 正式版如何创建一个Empty Applicatio ...

  8. Objective-C与C++的区别

    1.两者的最大相同:都是从C演化而来的面相对象语言,两者都兼容标准C语言 2.两者的最大不同:Objective-C提供了运行期动态绑定机制,而C++是编译静态绑定,并且通过嵌入类(多重继承)和虚函数 ...

  9. 【服务器环境搭建-Centos】tmpfs,【转载】

    转载来源:http://www.linuxidc.com/Linux/2013-12/93747.htm tmpfs介绍 tmpfs是一种虚拟内存文件系统,而不是块设备.是基于内存的文件系统,创建时不 ...

  10. 【matlab】读写文件

    save('pqfile.mat','M'); ('E:\我的坚果云\pqfile.mat','M'); 其他: http://blog.csdn.net/iqizheng/article/detai ...