思路
- 序列化:利用BFS层序遍历二叉树,节点与节点之间用
, 隔开;如果遇到空节点,则使用字母 X 代替,最终以字符串返回 - 反序列化:将序列化串,根据
, 分隔并保存在一个队列中;同时创建一个树节点的队列用来遍历到每层节点;遍历过程中,每次取出根节点和它可能的左右节点,然后判断这两个左右节点是否为 X ,如果是,则跳过说明为空节点;如果不是则加入其对应左右节点处,并加入队列中。
代码实现(java)
public class Codec {
public String serialize(TreeNode root) {
if(root == null) return "";
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(queue.size() > 0) {
TreeNode node = queue.poll();
if(node == null) {
sb.append("X").append(",");
continue;
}
sb.append(node.val).append(",");
queue.offer(node.left);
queue.offer(node.right);
}
return sb.toString();
}
public TreeNode deserialize(String data) {
if(data == "") return null;
Queue<String> nodeQueue = new LinkedList<>(Arrays.asList(data.split(",", -1)));
Queue<TreeNode> rootQueue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(nodeQueue.poll()));
rootQueue.offer(root);
while (!rootQueue.isEmpty()) {
TreeNode rootN = rootQueue.poll();
String left = nodeQueue.poll();
String right = nodeQueue.poll();
if (!"X".equals(left)) {
rootN.left = new TreeNode(Integer.parseInt(left));
rootQueue.offer(rootN.left);
}
if (!"X".equals(right)) {
rootN.right = new TreeNode(Integer.parseInt(right));
rootQueue.offer(rootN.right);
}
}
return root;
}
}
|