请实现两个函数,分别用来序列化和反序列化二叉树。
序列化二叉树:可以通过前序遍历二叉树来实现序列化,子节点为空的话就用#表示
序列化后的字符串:1 2 4 # # 3 5 # # 6 # #
其中用到indexof记录空格出现的位置:
indexOf() 方法有以下四种形式:
1、public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。int ch是字符对应的数字,如字符a对应的数字就是97。
2、public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
3、int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
4、int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
反序列化二叉树:已知参数是序列化后的二叉树字符串:先遍历这个字符串,记录空格出现的位置,第一个字符是根节点的值,然后指向字符串的下一个位置:
返回字符子串用了substring
substring() 方法返回字符串的子字符串。
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
参数:
beginIndex – 起始索引(包括), 索引从 0 开始。
endIndex – 结束索引(不包括)。
然后判断该节点是不是特殊字符,如果是就返回空,相当于先序遍历二叉树,先左子树,为空以后返回到根节点,然后右子树
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
//定义全局变量
private String deserializeStr;
//序列化
String Serialize(TreeNode root) {
if(root==null)
return "#";
return root.val+" "+Serialize(root.left)+" "+Serialize(root.right);
}
//反序列化
TreeNode Deserialize(String str) {
deserializeStr=str;
return Deserialize();
}
private TreeNode Deserialize(){
if(deserializeStr.length()==0)
return null;
//找到空格出现的位置
int index=deserializeStr.indexOf(" ");
//取节点
String node=index== -1 ? deserializeStr:deserializeStr.substring(0,index);
//截取字符串往后移动
deserializeStr=index == -1 ? "" :deserializeStr.substring(index+1);
if(node.equals("#"))
return null;
int val=Integer.valueOf(node);
TreeNode t=new TreeNode(val);
t.left = Deserialize();
t.right = Deserialize();
return t;
}
}