[剑指 Offer 37. 序列化二叉树](剑指 Offer 37. 序列化二叉树)
public class Codec {
public String serialize(TreeNode root) {
List<String> list = new ArrayList<>();
Deque<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(node == null) {
list.add(" ");
continue;
} else {
list.add("" + node.val);
}
q.offer(node.left);
q.offer(node.right);
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < list.size(); i++) {
if(i > 0) {
sb.append(",");
}
sb.append(list.get(i));
}
return sb.toString();
}
public TreeNode deserialize(String data) {
int pos = 0;
String[] split = data.split(",");
if(split.length == 0 || " ".equals(split[0])) return null;
TreeNode root = new TreeNode(Integer.parseInt(split[pos++]));
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while(q.size() > 0) {
int size = q.size();
int len = size;
List<TreeNode> list = new ArrayList<>();
List<String> valList = new ArrayList<>();
while(size-- > 0) {
list.add(q.poll());
valList.add(split[pos++]);
valList.add(split[pos++]);
}
for(int i = 0; i < len; i++) {
TreeNode node = list.get(i);
String leftS = valList.get(i * 2);
String rightS = valList.get(i * 2 + 1);
node.left = node.right = null;
if(!" ".equals(leftS)) {
node.left = new TreeNode(Integer.parseInt(leftS));
q.offer(node.left);
}
if(!" ".equals(rightS)) {
node.right = new TreeNode(Integer.parseInt(rightS));
q.offer(node.right);
}
}
}
return root;
}
}
|