解法
package com.wangxiaohu;
import java.util.LinkedList;
public class LeetCode297_1 {
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serializeTree(root, sb);
return sb.toString();
}
private void serializeTree(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append("#").append(",");
return;
}
serializeTree(root.left, sb);
serializeTree(root.right, sb);
sb.append(root.val).append(",");
}
public TreeNode deserialize(String data) {
LinkedList<String> nodes = new LinkedList<>();
for (String s : data.split(",")) {
nodes.addLast(s);
}
return deserializeStr(nodes);
}
private TreeNode deserializeStr(LinkedList<String> nodes) {
if (nodes.isEmpty()) {
return null;
}
String rootVal = nodes.removeLast();
if (rootVal.equals("#")) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(rootVal));
root.right = deserializeStr(nodes);
root.left = deserializeStr(nodes);
return root;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}