🌕🌕 剑指 Offer 37. 序列化二叉树
2022年10月10日
- algorithm
🌕🌕 剑指 Offer 37. 序列化二叉树
难度: 🌕🌕
问题描述
解法 1 - 层序
/**
* 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 "";
}
StringBuilder sb = new StringBuilder();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
int len = queue.size();
for(int i = 0; i < len; i ++) {
TreeNode cur = queue.poll();
if(cur == null) {
sb.append("#").append(',');
continue;
}
sb.append(cur.val).append(',');
queue.offer(cur.left);
queue.offer(cur.right);
}
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
int len = data.length();
if(len == 0) {
return null;
}
String[] arr = data.split(",");
TreeNode root = new TreeNode(Integer.valueOf(arr[0]));
int index = 1;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode cur = queue.poll();
String l = arr[index];
if(l.equals("#")) {
index ++;
} else {
TreeNode left = new TreeNode(Integer.valueOf(l));
cur.left = left;
queue.offer(left);
index ++;
}
String r = arr[index];
if(r.equals("#")) {
index ++;
} else {
TreeNode right = new TreeNode(Integer.valueOf(r));
cur.right = right;
queue.offer(right);
index ++;
}
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
输出 1
解法 2 - 先序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// 思路:
// 先序遍历 - 空节点也入队
int index = 0;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null) {
return "";
}
StringBuilder sb = new StringBuilder();
mySol1(root, sb);
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
private void mySol1(TreeNode root, StringBuilder sb) {
// 递归终止条件
if(root == null) {
sb.append("#").append(",");
return;
}
// root != null
sb.append(root.val).append(',');
mySol1(root.left, sb);
mySol1(root.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.equals("")) {
return null;
}
String[] arr = data.split(",");
int len = arr.length;
return mySol2(arr, len);
}
private TreeNode mySol2(String[] arr, int len) {
// 递归终止条件
if(index == len) {
return null;
}
String cur = arr[index]; // 根节点
if(cur.equals("#")) {
// 说明是个 空节点
index ++;
return null;
}
// 非空节点
TreeNode res = new TreeNode(Integer.valueOf(cur));
index ++;
res.left = mySol2(arr, len);
res.right = mySol2(arr, len);
return res;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));