标签:
请实现两个函数,分别用来序列化和反序列化二叉树
/*
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();
mySer(sb, root);
return sb.toString();
}
public void mySer(StringBuilder sb, TreeNode root) {
if (root == null) {
sb.append("$,");
return;
}
sb.append(String.valueOf(root.val));
sb.append(",");
mySer(sb, root.left);
mySer(sb, root.right);
return;
}
int point = -1;
TreeNode Deserialize(String str) {
String[] strArr = str.split(",");
if (strArr[0].equals("$")) {
return null;
}
TreeNode root = myDeser(strArr);
return root;
}
public TreeNode myDeser(String[] str) {
point++;
if (point == str.length) {
return null;
}
if (!str[point].equals("$")) {
TreeNode node = new TreeNode(Integer.parseInt(str[point]));
node.left = myDeser(str);
node.right = myDeser(str);
return node;
} else {
return null;
}
}
}
标签:
原文地址:http://www.cnblogs.com/rosending/p/5721944.html