题目描述
解题思路
前序遍历
public class Codec {
String SEP = ",";
String NULL = "#";
public String serialize(TreeNode root) {
if (root == null) {
return NULL + SEP;
}
return root.val + SEP + serialize(root.left) + serialize(root.right);
}
public TreeNode deserialize(String data) {
String[] splitData = data.split(SEP);
LinkedList<String> nodes = new LinkedList<>();
for (String s : splitData) {
nodes.add(s);
}
return deserialize(nodes);
}
public TreeNode deserialize(LinkedList<String> nodes) {
if (nodes.isEmpty()) return null;
String firstNode = nodes.removeFirst();
if (firstNode.equals(NULL)) return null;
TreeNode root = new TreeNode(Integer.parseInt(firstNode));
root.left = deserialize(nodes);
root.right = deserialize(nodes);
return root;
}
}