297 Serialize and Deserialize Binary Tree
ref 297. Serialize and Deserialize Binary Tree
Difficulty: Hard
Company Tag: Linkedin Google Uber Facebook Amazon Microsoft Yahoo Bloomberg
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.
For example, you may serialize the following tree
1
/ \
2 3
/ \
4 5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ 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.
分析
这种serialization的方法很好看,用的是preOrder, 用途很广,做法也是挺漂亮的
cc150里面的找一个超大的树A是不是另一个超大的树B的子树,也可以先压扁,然后如果一个树的序列是另外一个数序列的子串,那么就是子树
snapchat有个面经,“是从binary tree里找出所有duplicate的树。return应该是一个key value pair,key是任何形式表示的树,value是这个树出现的次数。我的大致思路就是对每个node,做出以这个node为根的树的serialization。然后以这个serialization为key扔到hashtable里就可以。followup就是问时间和空间复杂度。”也是可以把每一个node压扁了,然后用hashSet统计出现的次数
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
getSerialization(root, sb);
return sb.toString();
}
private void getSerialization(TreeNode root, StringBuilder sb) {
if(root == null) {
sb.append("#").append(",");
return;
}
sb.append(root.val + ",");
getSerialization(root.left, sb);
getSerialization(root.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] nodes = data.split(",");
Queue<String> queue = new LinkedList<>();
queue.addAll(Arrays.asList(nodes));
return getTree(queue);
}
private TreeNode getTree(Queue<String> queue) {
String cur = queue.poll();
TreeNode root = null;
if(cur.equals("#")) {
return root;
} else {
root = new TreeNode(Integer.parseInt(cur));
root.left = getTree(queue);
root.right = getTree(queue);
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));