面试题37.序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树。
观察题目示例,序列化的字符串实际上是二叉树的 “层序遍历”(BFS)结果,本文也采用层序遍历。
通常使用的前序、中序、后序、层序遍历记录二叉树的信息不完整,即可能对应着多种二叉树结果。
题目要求的 “序列化” 和 “反序列化” 是 可逆 操作。因此,序列化的字符串应携带 “完整的” 二叉树信息,即拥有单独表示二叉树的能力。
为使反序列化可行,考虑将越过叶节点后的 nullnull 也看作是节点。在此基础上,对于列表中任意某节点 nodenode ,其左子节点 node.leftnode.left 和右子节点 node.rightnode.right 在序列中的位置都是 唯一确定 的。
参考代码
/**
* 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) {
StringBuilder s = new StringBuilder();
if(root == null) {
return "[]";
}
s.append("[");
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode t = queue.poll();
if(t != null) {
queue.add(t.left);
queue.add(t.right);
s.append(t.val + ",");
}else{
s.append("null,");
}
}
//去掉多余的逗号
s.deleteCharAt(s.length() - 1);
s.append("]");
return s.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null || data.equals("") || data.equals("[]")) {
return null;
}
//删除data首尾的括号
String s = data.substring(1,data.length()-1);
String[] nodes = s.split(",");
TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
//利用层次遍历顺序(保存的是节点的值),还原二叉树(需要:队列+节点计数遍历序列)
//特点:叶子节点的左右孩子为null null,在层次遍历序列化的时候成对且相邻出现
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while(!queue.isEmpty()) {
TreeNode t = queue.poll();
if(!nodes[i].equals("null")) {
//创建当前节点的左孩子
t.left = new TreeNode(Integer.parseInt(nodes[i]));
//左孩子入队列
queue.add(t.left);
}
i++;
if(!nodes[i].equals("null")) {
//创建当前节点的右孩子
t.right = new TreeNode(Integer.parseInt(nodes[i]));
// 右孩子入队列
queue.add(t.right);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));