题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
解题思路
输入非要用char*
,本菜被弄得头大,看了评论区知道了用指向指针的指针可以返回修改过的指针,*(str)++
真香,还是java香
Code
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
char* Serialize(TreeNode *root) {
if(!root) return nullptr;
string str;
str = SerializeCore(root);
char *result = new char[str.length()+1];
for(int i = 0; i<str.length(); i++) {
result[i] = str[i];
}
result[str.length()] = '\0';
return result;
}
string SerializeCore(TreeNode *root) {
string str;
if(!root) {
str += '#';
return str;
}
str += to_string(root->val)+',';
str += SerializeCore(root->left);
str += SerializeCore(root->right);
return str;
}
TreeNode* Deserialize(char *str) {
if(!str) return nullptr;
TreeNode *root = DeserializeCore(&str);
return root;
}
TreeNode* DeserializeCore(char **str) {
if(**str == '#') {
(*str)++;
return nullptr;
}
int val = 0;
while(**str != '\0' && **str != ',') {
val = val*10 + **str-'0';
(*str)++;
}
TreeNode *root = new TreeNode(val);
if(**str == '\0') return root;
else (*str)++;
root->left = DeserializeCore(str);
root->right = DeserializeCore(str);
return root;
}
};
- java
private int index = -1;
String Serialize(TreeNode root) {
if(root == null) return "#,"; //分隔符用.号过不了。。
StringBuilder sb = new StringBuilder();
sb.append(root.val + ",");
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));
return sb.toString();
}
TreeNode Deserialize(String str) {
index++;
String[] nodes = str.split(",");
TreeNode root = null;
if(!nodes[index].equals("#")) {
root = new TreeNode(Integer.valueOf(nodes[index]));
root.left = Deserialize(str);
root.right = Deserialize(str);
}
return root;
}
总结
String
是不可变对象,因此操作起来困难了许多,需要加入全局变量。- 所以可以改用线程不安全的
StringBuilder
进行操作 - 注意
StringBuilder
的删除方法是delete(start, end)(不含end)
和deleteCharAt(index)
,以及indexOf(String str)(非char)
/*
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) {
if(root == null) return "#";
StringBuilder sb = new StringBuilder();
sb.append(root.val + ".");
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));
return sb.toString();
}
TreeNode Deserialize(String str) {
StringBuilder sb = new StringBuilder(str);
TreeNode root = DeserializeCore(sb);
return root;
}
TreeNode DeserializeCore(StringBuilder sb) {
if(sb.charAt(0) == '#') {
sb.deleteCharAt(0);
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(sb.substring(0, sb.indexOf("."))));
sb.delete(0, sb.indexOf(".")+1);
root.left = DeserializeCore(sb);
root.right = DeserializeCore(sb);
return root;
}
}