原题网址:https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
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 5as
"[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.
方法一:深度优先+递归。
/**
* 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) {
if (root==null) return "[]";
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(root.val);
sb.append(",");
sb.append(serialize(root.left));
sb.append(",");
sb.append(serialize(root.right));
sb.append("]");
// System.out.printf("serialize: %s\n", sb.toString());
return sb.toString();
}
private int pos;
private TreeNode parse(String data) {
if (data.charAt(pos) != '[') return null;
pos ++;
if (data.charAt(pos) == ']') {
pos ++;
return null;
}
int val = 0;
boolean negative = false;
if (data.charAt(pos) == '-') {
negative = true;
pos ++;
}
for(;pos<data.length() && data.charAt(pos)>='0' && data.charAt(pos)<='9'; pos ++) {
val = val*10+data.charAt(pos)-'0';
}
if (negative) val = -val;
TreeNode node = new TreeNode(val);
// System.out.printf("val=%d\n", val);
if (data.charAt(pos) != ',') return null;
pos ++;
node.left = parse(data);
if (data.charAt(pos) != ',') return null;
pos ++;
node.right = parse(data);
if (data.charAt(pos) != ']') return null;
pos ++;
return node;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
pos = 0;
return parse(data);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
方法二:广度优先。
/**
* 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) {
if (root == null) return "null";
StringBuilder sb = new StringBuilder();
sb.append(root.val);
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root.left);
list.add(root.right);
while (!list.isEmpty()) {
TreeNode node = list.remove();
sb.append(",");
if (node == null) sb.append("null");
else {
sb.append(node.val);
list.add(node.left);
list.add(node.right);
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
int pos = 0;
pos = parse(data, pos);
TreeNode root = parsed;
if (root == null) return null;
LinkedList<TreeNode> nodes = new LinkedList<>();
nodes.add(root);
do {
TreeNode node = nodes.remove();
pos = parse(data, pos);
node.left = parsed;
if (node.left != null) nodes.add(node.left);
pos = parse(data, pos);
node.right = parsed;
if (node.right != null) nodes.add(node.right);
} while (!nodes.isEmpty());
return root;
}
private TreeNode parsed;
private int parse(String data, int pos) {
if (data.charAt(pos) == 'n') {
pos += 4;
if (pos<data.length()) pos ++;
parsed = null;
return pos;
}
boolean negative = false;
int val = 0;
if (data.charAt(pos) == '-') {
negative = true;
pos ++;
}
for(; pos<data.length() && data.charAt(pos) >= '0' && data.charAt(pos) <= '9'; pos ++) {
val = val * 10 + data.charAt(pos) - '0';
}
if (pos<data.length()) pos ++;
if (negative) val = -val;
parsed = new TreeNode(val);
return pos;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
方法三:广度优先,按层进行序列化。
/**
* 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();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.remove();
if (sb.length()>0) sb.append(",");
if (node == null) sb.append("#");
else {
sb.append(node.val);
queue.add(node.left);
queue.add(node.right);
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if ("#".equals(data)) return null;
String[] vals = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
for(int i=1; i<vals.length; i+=2) {
TreeNode node = queue.remove();
if (!"#".equals(vals[i])) {
TreeNode left = new TreeNode(Integer.parseInt(vals[i]));
node.left = left;
queue.add(left);
}
if (!"#".equals(vals[i+1])) {
TreeNode right = new TreeNode(Integer.parseInt(vals[i+1]));
node.right = right;
queue.add(right);
}
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));