Problem: 297. 二叉树的序列化与反序列化
题目描述
思路
利用二叉树的先序遍历将其序列与反序列化
1.序列化:利用先序遍历将其转换为一个字符串;
2.反序列化:先将其每个字符分割出来,再利用递归将其分解构造二叉树(由于序列化使用的先序遍历,则反序列化也对应要使用先序遍历;同时由于序列化中有字符记录了二叉树为空的情况,则可以直接构造处二叉树,而不是需要先序、后序、和中序搭配来构造)
复杂度
时间复杂度:
O ( n ) O(n) O(n);其中 n n n为二叉树节点的个数
空间复杂度:
O ( n ) O(n) O(n)
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Codec {
String SEP = ",";
String NULL = "#";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
}
private void serialize(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append(NULL).append(SEP);
return;
}
sb.append(root.val).append(SEP);
serialize(root.left, sb);
serialize(root.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
LinkedList<String> nodes = new LinkedList<>();
for (String s : data.split(SEP)) {
nodes.addLast(s);
}
return deserialize(nodes);
}
private TreeNode deserialize(LinkedList<String> nodes) {
if (nodes.isEmpty()) {
return null;
}
String first = nodes.removeFirst();
if (first.equals(NULL)) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(first));
root.left = deserialize(nodes);
root.right = deserialize(nodes);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));