序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
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 tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。
Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
说明: 不要使用类的成员 / 全局 / 静态变量来存储状态,你的序列化和反序列化算法应该是无状态的。
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
这道题在 LeetCode 中的难度为最高级别 困难
,但是实际体验真的很简单,主要考的还是二叉数的遍历。该题的序列化和反序列化各需一个前序遍历,真的非常简单。
public class Codec {
public String serialize(TreeNode root) {
return serializeHelper(root, "");
}
private String serializeHelper(TreeNode root, String str) {
// 基线条件:遇到 null 时构造 “null” 字符串
if (root == null)
return str + "null,";
// 构造返回字符串 str
str += String.valueOf(root.val) + ",";
str = serializeHelper(root.left, str);
str = serializeHelper(root.right, str);
return str;
}
public TreeNode deserialize(String data) {
String[] data_array = data.split(",");
// 根据前序遍历的结果逆向构造二叉树时,因为要从左到右操作前序遍历结果,所以使用队列更适合
Queue list = new LinkedList<>(Arrays.asList(data_array));
return deserializeHelper(list);
}
private TreeNode deserializeHelper(Queue queue) {
if (queue.peek().equals("null")) {
queue.poll();
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(queue.poll()));
root.left = deserializeHelper(queue);
root.right = deserializeHelper(queue);
return root;
}
}
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def helper(root, string):
if not root:
string += "None,"
else:
string += str(root.val)+","
string = helper(root.left, string)
string = helper(root.right, string)
return string
return helper(root, '')
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def helper(l: list):
if(l[0] == "None"):
l.pop(0)
return None
root = TreeNode(l.pop(0))
root.left = helper(l)
root.right = helper(l)
return root
data_list = data.split(',')
root = helper(data_list)
return root