public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root==null) return "";
Queue<TreeNode> queue=new LinkedList<>();
StringBuilder res=new StringBuilder();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode cur=queue.poll();
if(cur==null){
res.append("n ");
continue;
}
res.append(cur.val+" ");
queue.offer(cur.left);
queue.offer(cur.right);
}
return res.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data=="") return null;
Queue<TreeNode> queue=new LinkedList<>();
String[] values=data.split(" ");
TreeNode root=new TreeNode(Integer.parseInt(values[0]));
queue.offer(root);
for(int i=1;i<values.length;i++){
TreeNode cur=queue.poll();
if(!values[i].equals("n")){
TreeNode left=new TreeNode(Integer.parseInt(values[i]));
cur.left=left;
queue.offer(left);
}
if (!values[++i].equals("n")) {
TreeNode right = new TreeNode(Integer.parseInt(values[i]));
cur.right = right;
queue.add(right);
}
}
return root;
}
}
网友评论