public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
return String.join(",", serialize(root, new LinkedList<>()));
}
private List<String> serialize(TreeNode treeNode, List<String> valueList) {
if (treeNode == null) {
valueList.add("null");
} else {
valueList.add(String.valueOf(treeNode.val));
serialize(treeNode.left, valueList);
serialize(treeNode.right, valueList);
}
return valueList;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] values = data.split(",");
List<String> valueList = new LinkedList<>(Arrays.asList(values));
return deserialize(valueList);
}
private TreeNode deserialize(List<String> valueList) {
if (valueList.get(0).equals("null")) {
valueList.remove(0);
return null;
}
TreeNode treeNode = new TreeNode(Integer.parseInt(valueList.get(0)));
valueList.remove(0);
treeNode.left = deserialize(valueList);
treeNode.right = deserialize(valueList);
return treeNode;
}
}
image.png
网友评论