import java.util.*;
public class Codec {
String sequence = "";
public String serialize(TreeNode root) {
if (root == null) {
sequence += "null,";
return sequence;
}
sequence += root.val + ",";
serialize(root.left);
serialize(root.right);
return sequence;
}
public TreeNode deserialize(String data) {
String[] datas = data.split(",");
LinkedList<String> strings = new LinkedList<>(Arrays.asList(datas));
return createTree(strings);
}
public TreeNode createTree(LinkedList<String> strings) {
String s = strings.get(0);
if (s.equals("null")) {
strings.remove(0);
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(s));
strings.remove(0);
root.left = createTree(strings);
root.right = createTree(strings);
return root;
}
}
二叉树的序列化与反序列化
最新推荐文章于 2023-05-22 20:53:18 发布