Binary Tree Serialization (Level-Order)
LeetCode 297 二叉树序列化与反序列化:层序 BFS + 空节点占位。
#resource / algorithm
#type / howto
#status / evergreen
#ds / tree
#algo / bfs
#source / leetcode
[!info] related notes 算法面试题型 MOC 二叉树高频题
Binary Tree Serialization (Level-Order)
LeetCode: https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
思路
- BFS 输出节点值。
- 遇到空孩子也输出占位符(例如
#),否则结构会丢。 - 反序列化时用队列逐层挂孩子。
Java Template
import java.util.*;
public class Codec {
private static final String SEP = ",";
private static final String NIL = "#";
public String serialize(TreeNode root) {
if (root == null) return NIL;
StringBuilder sb = new StringBuilder();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode cur = q.poll();
if (cur == null) {
sb.append(NIL).append(SEP);
continue;
}
sb.append(cur.val).append(SEP);
q.add(cur.left);
q.add(cur.right);
}
return sb.toString();
}
public TreeNode deserialize(String data) {
if (data == null || data.isEmpty() || data.equals(NIL)) return null;
String[] parts = data.split(SEP);
int idx = 0;
TreeNode root = node(parts[idx++]);
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode cur = q.poll();
if (cur == null) continue;
if (idx < parts.length) {
cur.left = node(parts[idx++]);
q.add(cur.left);
}
if (idx < parts.length) {
cur.right = node(parts[idx++]);
q.add(cur.right);
}
}
return root;
}
private TreeNode node(String s) {
if (s.equals(NIL) || s.isEmpty()) return null;
return new TreeNode(Integer.parseInt(s));
}
}