题目:
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
思路:
这里我选择先序遍历进行一个序列化,因为考虑到反序列化的时候,如果序列化是按先序的那么序列化后面的结点是前面结点的孩子结点,这样再去考虑递归好不好做反序列化
代码:
序列化的很简单,递归先序遍历即可
StringBuilder sb = new StringBuilder();
String Serialize(TreeNode root) {
if(root == null){
return "#";
}
processSerialize(root);
return sb.toString();
}
void processSerialize(TreeNode node){
if (node == null){
sb.append("#!");
return;
}
sb.append(node.val);
sb.append("!");
processSerialize(node.left);
processSerialize(node.right);
}
反序列化:
按照题目规则,把值的连接符去掉后可生成一个数组,然后根据这个数组用递归恢复成原来的二叉树,每一层的思路也很简单:
1.新建结点
2.递归求结点左子树
3.递归求结点右子树
4.递归停止条件:本层要处理的数的下标越界或值为#(根据题目要求#表示null)
一个主意的点:下标要处理成全局的,因为反序列化过程不会往前走,只会往后走,如果用局部变量,递归返回本层的时候就会出错了
代码:
int index = 0;
TreeNode Deserialize(String str) {
if (str == null || str.length() == 0){
return null;
}
String[] data = str.split("!");
return processDeserialize(data);
}
TreeNode processDeserialize(String[] data){
if (index >= data.length){
return null;
}
if (data[index].equals("#")){
index++;
return null;
}
TreeNode node = new TreeNode(Integer.valueOf(data[index]));
index++;
node.left = processDeserialize(data);
node.right = processDeserialize(data);
return node;
}
完整:
public class Solution {
int index = 0;
StringBuilder sb = new StringBuilder();
String Serialize(TreeNode root) {
if(root == null){
return "#";
}
processSerialize(root);
return sb.toString();
}
TreeNode Deserialize(String str) {
if (str == null || str.length() == 0){
return null;
}
String[] data = str.split("!");
return processDeserialize(data);
}
TreeNode processDeserialize(String[] data){
if (index >= data.length){
return null;
}
if (data[index].equals("#")){
index++;
return null;
}
TreeNode node = new TreeNode(Integer.valueOf(data[index]));
index++;
node.left = processDeserialize(data);
node.right = processDeserialize(data);
return node;
}
void processSerialize(TreeNode node){
if (node == null){
sb.append("#!");
return;
}
sb.append(node.val);
sb.append("!");
processSerialize(node.left);
processSerialize(node.right);
}
}