剑指Offer_61_序列化二叉树
题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
解题思路
使用前序遍历,将遇到的结点添加到字符串中,遇到null则将一个#添加要序列化字符串中。反序列化时,每次读取根结点,然后读取其左结点,遇到#(null)时,返回上层。
实现
/*树结点定义*/
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
/*实现*/
public class Solution {
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("#,");
return;
}
sb.append(root.val + ",");
serialize(root.left, sb);
serialize(root.right, sb);
}
private class Result{
TreeNode node;
int pos;
Result(TreeNode node, int pos){
this.node = node;
this.pos = pos;
}
}
TreeNode Deserialize(String str) {
if (str == null || str.length() <= 0) return null;
String[] strs = str.split(",");
Result re = deserialize(strs, 0);
return re.node;
}
private Result deserialize(String[] str, int i) {
TreeNode root = null;
if (i < str.length - 1){
if ("#".equals(str[i])) return new Result(null, i+1);
root = new TreeNode(Integer.parseInt(str[i]));
Result l = deserialize(str, i + 1);
root.left = l.node;
Result r = deserialize(str, l.pos);
root.right = r.node;
return new Result(root, r.pos);
}
return new Result(root, i+1);
}
}