目录结构
1.题目
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
层序遍历
public class Offer37 {
@Test
public void test() {
TreeNode root = new TreeNode(1, new TreeNode(2), new TreeNode(3, new TreeNode(4), new TreeNode(5)));
System.out.println(serialize(root));
TreeNode.printf(deserialize(serialize(root)));
}
public String serialize(TreeNode root) {
if (root == null) {
return "[]";
}
List<Integer> list = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int count = 1;
while (!queue.isEmpty() && count > 0) {
TreeNode tmp = queue.poll();
if (tmp == null) {
list.add(null);
} else {
count--;
list.add(tmp.val);
queue.add(tmp.left);
queue.add(tmp.right);
count += tmp.left == null ? 0 : 1;
count += tmp.right == null ? 0 : 1;
}
}
return String.valueOf(list).replace(" ", "");
}
public TreeNode deserialize(String data) {
if ("[]".equals(data)) {
return null;
}
String[] strings = data.substring(1, data.length() - 1).split(",");
TreeNode root = new TreeNode(Integer.parseInt(strings[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int p = 1, len = strings.length;
while (!queue.isEmpty()) {
TreeNode tmp = queue.poll();
if (p < len && !"null".equals(strings[p])) {
tmp.left = new TreeNode(Integer.parseInt(strings[p]));
queue.add(tmp.left);
}
p++;
if (p < len && !"null".equals(strings[p])) {
tmp.right = new TreeNode(Integer.parseInt(strings[p]));
queue.add(tmp.right);
}
p++;
}
return root;
}
}
- 时间复杂度:
- 空间复杂度: