题解 | #序列化二叉树#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
import java.util.Queue;
import java.util.LinkedList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
StringBuffer sb = new StringBuffer();
Queue<TreeNode>q = new LinkedList<TreeNode>();
q.offer(root);
while(!q.isEmpty()){
TreeNode t = q.poll();
if(t!=null){
sb.appe***al);
sb.append(",");
q.offer(t.left);
q.offer(t.right);
}
else{
sb.append("#");
sb.append(",");
}
}
return sb.toString();
}
TreeNode Deserialize(String str) {
String[] s = str.split(",");
if(s[0].equals("#")) return null;
int i = 0;
Queue<TreeNode>q = new LinkedList<TreeNode>();
TreeNode root = new TreeNode(Integer.parseInt(s[i]));
i++;
q.offer(root);
while(!q.isEmpty() && i<s.length){
TreeNode t = q.poll();
if(s[i].equals("#"))
t.left = null;
else{
TreeNode k = new TreeNode(Integer.parseInt(s[i]));
t.left = k;
q.offer(k);
}
i++;
if(s[i].equals("#"))
t.right = null;
else{
TreeNode k = new TreeNode(Integer.parseInt(s[i]));
t.right = k;
q.offer(k);
}
i++;
}
return root;
}
}
String 转int String转string数组