297. 二叉树的序列化与反序列化
2021-09-06 本文已影响0人
justonemoretry
image.png
image.png
image.png
解法
深度优先遍历解法
/**
* 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) {
if (root == null) {
return "X";
}
// 先序遍历,进行序列化
String left = serialize(root.left);
String right = serialize(root.right);
return root.val + "," + left + "," + right;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
List<String> dataList = new LinkedList<String>(Arrays.asList(data.split(",")));
return treeNodeDeserialize(dataList);
}
public TreeNode treeNodeDeserialize(List<String> dataList) {
String item = dataList.get(0);
dataList.remove(0);
if (item.equals("X")) {
return null;
}
// 递归先序遍历,构建二叉树
TreeNode node = new TreeNode(Integer.valueOf(item));
TreeNode left = treeNodeDeserialize(dataList);
TreeNode right = treeNodeDeserialize(dataList);
node.left = left;
node.right = right;
return node;
}
}
// 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));
广度优先遍历解法
/**
* 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) {
if (root == null) {
return "X";
}
// 先序遍历,进行序列化
Queue<TreeNode> q = new LinkedList<>();
List<String> res = new ArrayList<>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode node = q.poll();
if (node != null) {
res.add(String.valueOf(node.val));
q.offer(node.left);
q.offer(node.right);
} else {
res.add("X");
}
}
return String.join(",", res);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.equals("X")) {
return null;
}
List<String> dataList = new ArrayList<>(Arrays.asList(data.split(",")));
// 利用队列,从上往下构造树
Queue<TreeNode> q = new LinkedList<>();
TreeNode root = new TreeNode(Integer.valueOf(dataList.get(0)));
q.offer(root);
int cur = 1;
// 广度优先遍历的反过程,先将分配好的左右子节点放到队列中,
// 用于后续给这些子节点按序分配子节点
while (cur < dataList.size()) {
TreeNode node = q.poll();
String left = dataList.get(cur);
String right = dataList.get(cur + 1);
if (!left.equals("X")) {
TreeNode leftNode = new TreeNode(Integer.valueOf(left));
node.left = leftNode;
q.offer(leftNode);
}
if (!right.equals("X")) {
TreeNode rightNode = new TreeNode(Integer.valueOf(right));
node.right = rightNode;
q.offer(rightNode);
}
// 每次取两个子节点
cur += 2;
}
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));