class Solution{
String Serialize(TreeNode root) {
StringBuffer str= new StringBuffer();
preSearch(root, str);
return str.toString();
}
//前序遍历
void preSearch(TreeNode node,StringBuffer s){
if(node==null){//空则用特殊字符表示
s.append(",$");
return;
}
s.append(","+node.val);
preSearch(node.left,s);
preSearch(node.right,s);
}
//反序列化
int index = -1;
TreeNode Deserialize(String str) {
str = str.substring(1);
String[] array = str.split(",");
int len = array.length;
for(String s : array)
s.replace(',', ' ');
if(len == 1)
return null;
TreeNode root = new TreeNode (Integer.parseInt(array[++index]));//CHAR变为int
root.left = des(array);
root.right = des(array);
return root;
}
TreeNode des(String[] str){
TreeNode node = null;
if(++index < str.length){
String ele = str[index];
if(!ele .equals("$") ){
node = new TreeNode(Integer.parseInt(ele));
node.left = des(str);
node.right = des(str);
}
}
return node;
}
}
序列化二叉树
最新推荐文章于 2022-04-29 11:44:00 发布