方法:BFS
算法思想:
时间复杂度:
空间复杂度:
边界条件:
补充知识:/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root==null) return "[]"; //判空
StringBuilder res=new StringBuilder("["); //string可变,常如此用来拼接
Queue<TreeNode> q=new LinkedList<>(){{add(root);}};//注意添加root的格式
while(!q.isEmpty()){
TreeNode t=q.poll();
if(t!=null){ //根节点不为空
res.append(t.val+","); //结果字符串尾加
q.add(t.left); //队列加左右
q.add(t.right);
}else
res.append("null,");
}
res.deleteCharAt(res.length()-1); //不太明白??
res.append("]"); //注意格式,要有最后的闭合
return res.toString(); //必须返回string
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.equals("[]")) return null; //对应序列化
String[] s=data.substring(1,data.length()-1).split(","); //字符串的裁剪方法,左右范围?substring小写
TreeNode root= new TreeNode(Integer.parseInt(s[0])); //字符串转Integer
Queue <TreeNode> q=new LinkedList<>(){{add(root);}}; //加入队列
int i=1;
while(!q.isEmpty()){
TreeNode node=q.poll(); //队列出
if(!s[i].equals("null")){ //注意string的判断空
node.left=new TreeNode(Integer.parseInt(s[i])); //构建TreeNode节点
q.add(node.left); //加入队列下次弹出
} i++; //指针继续走
if(!s[i].equals("null")){
node.right=new TreeNode(Integer.parseInt(s[i]));
q.add(node.right);
} i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));