297. Serialize and Deserialize Binary Tree (Hard)
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 ashow 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.
Solution 1: BFS O(n);O(w) O(n);O(n)
Use BFS to traverse the tree in level order and use string "#"(pound) to represent null nodes.
When deserialize the string, assign left and right child for each non-null node, and add the non-null children to the queue, which will be handled later.
public String serialize(TreeNode root) { //O(n);O(w)
if (root == null) {
return "";
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
StringBuilder res = new StringBuilder();
while (!queue.isEmpty()) {
TreeNode head = queue.poll();
if (head == null) {
res.append("#,");
continue;
}
res.append(head.val + ",");
queue.offer(head.left);
queue.offer(head.right);
}
return res.toString();
}
public TreeNode deserialize(String data) { //O(n);O(n)
if (data == "") {
return null;
}
String[] values = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(values[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
for (int i = 1; i < values.length; i++) {
TreeNode parent = queue.poll();
if (!values[i].equals("#")) {
TreeNode left = new TreeNode(Integer.parseInt(values[i]));
parent.left = left;
queue.offer(left);
}
if (!values[++i].equals("#")) {
TreeNode right = new TreeNode(Integer.parseInt(values[i]));
parent.right = right;
queue.offer(right);
}
}
return root;
}
Solution 2: Recursive, preorder
/**
* Recursive O(n); O(h)
* use preorder traversal with root and a StringBuilder object.
* Append current node's val and a delimiter.
* Then recurse down to left and right subtrees.
* Base case:
* If node is null, append a null node and a delimiter.
* => 1,2,#,#,3,4,#,#,5,#,#,
*/
public String serializeB(TreeNode root) {
StringBuilder sb = new StringBuilder();
return buildString(root, sb).toString();
}
private StringBuilder buildString(TreeNode root, StringBuilder sb) {
if (root == null) {
return sb.append("#").append(",");
}
sb.append(root.val).append(",");
buildString(root.left, sb).append(",");
buildString(root.right, sb);
return sb;
}
/**
* Recursive O(n); O(n)
* Same as preorder traversal.
* Split data by "," and use Queue to store strings.
* Poll a value string from the queue.
* If null node, return null.
* Create a tree node with value.
* Then build left and right subtrees recursively.
*/
public TreeNode deserializeB(String data) {
Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(",")));
return buildTree(queue);
}
private TreeNode buildTree(Queue<String> queue) {
String head = queue.poll();
if ("#".equals(head)) {
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(head));
root.left = buildTree(queue);
root.right = buildTree(queue);
return root;
}