
int index = -1;
String Serialize(TreeNode root) {
if (root == null) {
return "#";
}
return root.val+","+Serialize(root.left)+","+Serialize(root.right);
}
TreeNode Deserialize(String str) {
String[] s = str.split(",");
index++;
int len = s.length;
if (index>len) {
return null;
}
TreeNode treeNode = null;
if (!s[index].equals("#")) {
treeNode = new TreeNode(Integer.parseInt(s[index]));
treeNode.left = Deserialize(str);
treeNode.right = Deserialize(str);
}
return treeNode;
}
本文介绍了一种二叉树的序列化和反序列化方法,使用递归方式将二叉树节点转化为字符串形式,并能从该字符串还原为原始的二叉树结构。此方法对于树形数据结构的操作十分有用。
105

被折叠的 条评论
为什么被折叠?



