Problem
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.
思路
- Serialization
- use bfs to traverse the tree. need a queue
- a stringbuider
- put root to the queue
- when the queue is not empty
- add ','
- check left node of current node
- null then add '#'
- not null then add val
- check right node of current node the way as the left node
- Deserialization
- split the data with ','
- create root node with the first element
- create left node and right node and connect to root node level by level, so need a queue
- maintain an index for the array from splitting string
- put root node to the queue
- while the queue is not empty
- check left node and right node
- not #, then construct, connect, enqueue
- #, do nothing
public String serialize(TreeNode root) {
if (root == null) return "";
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
sb.append(root.val);
while (!queue.isEmpty()) {
TreeNode curt = queue.poll();
sb.append(',');
if (curt.left == null) {
sb.append("#");
} else {
sb.append(curt.left.val);
queue.offer(curt.left);
}
sb.append(',');
if (curt.right == null) {
sb.append('#');
} else {
sb.append(curt.right.val);
queue.offer(curt.right);
}
}
return sb.toString();
}
public TreeNode deserialize(String data) {
if (data == null || data.length() == 0) return null;
String[] arr = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
int index = 1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode curt = queue.poll();
if (!"#".equals(arr[index])) {
TreeNode left = new TreeNode(Integer.parseInt(arr[index]));
curt.left = left;
queue.offer(left);
}
index++;
if (!"#".equals(arr[index])) {
TreeNode right = new TreeNode(Integer.parseInt(arr[index]));
curt.right = right;
queue.offer(right);
}
index++;
}
return root;
}
}