public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder res=ser_help(root,new StringBuilder());
return res;
}
public StringBuilder res(TreeNode root,StringBuilder str){
if(root==null){
str.append("null,");
return str;
}
//先序遍历
str.append(root.val);
str.append(",");
str=ser_help(root.left,str);
str=ser_help(right.left,str);
return str;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] str_word = data.split(",");
List<String> list_word = new LinkedList<String>(Arrays.asList(str_word));
return deser_help(list_word);
}
public TreeNode deser_help(List<String> li){
if(li.get(0).equals("null")){
li.remove(0);
return null;
}
TreeNode res = new TreeNode(Integer.valueOf(li.get(0)));
li.remove(0);
res.left = deser_help(li);
res.right = deser_help(li);
return res;
}
}
力扣题目:297. 二叉树的序列化与反序列化