题目
题解
dfs,进行先序遍历
public class Codec {
//树->字符串
public String serialize(TreeNode root) {
return rserialize(root,"");
}
//先序遍历
public String rserialize(TreeNode root,String str) {
if(root==null)
str+="none,";
else{
str+=str.valueOf(root.val)+",";
str=rserialize(root.left,str);
str=rserialize(root.right,str);
}
return str;
}
//字符串->树
public TreeNode deserialize(String data) {
String[] nodeArray=data.split(",");
List<String>nodeList=new LinkedList<>(Arrays.asList(nodeArray));
return rdeserialize(nodeList);
}
public TreeNode rdeserialize(List<String>nodeList) {
if(nodeList.get(0).equals("none")){
nodeList.remove(0);
return null;
}
TreeNode root=new TreeNode(Integer.valueOf(nodeList.get(0)));
nodeList.remove(0);
root.left=rdeserialize(nodeList);
root.right=rdeserialize(nodeList);
return root;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)