题目描述
请实现两个函数,分别用来序列化和反序列化二叉树。
题目链接:https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/
Java(广度优先遍历二叉树)
/**
* 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("[");
Queue<TreeNode> que= new LinkedList<TreeNode>();
que.add(root);
res.append(root.val);
res.append(",");
while(!que.isEmpty()){
TreeNode node = que.poll();
if(node.left != null){
res.append(node.left.val);
res.append(",");
que.add(node.left);
}
else
res.append("null,");
if(node.right != null){
res.append(node.right.val);
res.append(",");
que.add(node.right);
}
else
res.append("null,");
}
res.deleteCharAt(res.length() - 1);
res.append("]");
return res.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.equals("[]"))
return null;
String[] strs = data.substring(1, data.length() - 1).split(",");
Queue<TreeNode> que= new LinkedList<TreeNode>();
TreeNode root = new TreeNode(Integer.parseInt(strs[0]));
que.add(root);
int i = 1;
while(!que.isEmpty()){
TreeNode node = que.poll();
if(i >= strs.length) break;
if(!strs[i].equals("null")){
node.left = new TreeNode(Integer.parseInt(strs[i]));
que.add(node.left);
}
i++;
if(!strs[i].equals("null")){
node.right = new TreeNode(Integer.parseInt(strs[i]));
que.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));