# [编程题]序列化和反序列化二叉树（Java实现）

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13tqId=11214tPage=4rp=4ru=/ta/coding-interviewsqru=/ta/coding-interviews/question-ranking

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13tqId=11214tPage=4rp=4ru=/ta/coding-interviewsqru=/ta/coding-interviews/question-ranking

``````/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
StringBuilder ss=new StringBuilder();
String Serialize(TreeNode root) {
if(root==null){
ss.append("#,");
return ss.toString();
}
ss.append(root.val+",");
Serialize(root.left);
Serialize(root.right);
return ss.toString();
}
int index=-1;
TreeNode Deserialize(String str) {
if(str.equals("")||str.length()==0||str==null)
return null;
String[] str1=str.split(",");
return Deserialize(str1);
}
TreeNode Deserialize(String[] str) {
index++;
if(!str[index].equals("#")){
TreeNode root=new TreeNode(0);
root.val=Integer.valueOf(str[index]);
root.left=Deserialize(str);
root.right=Deserialize(str);
return root;
}
return null;
}
}
``````
• 英雄联盟
• 01:14:01