请实现两个函数,分别用来序列化和反序列化二叉树
序列化就是将二叉树以字符串输出,反序列化:根据自己输出的字符串,构建二叉树。
这里先序遍历输出,且为了方便反序列化,各个节点“,”隔开,且叶子节点后用"#,"隔开
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null;
public TreeNode(int val) { this.val = val;
}
} */ public class Solution { int index; String Serialize(TreeNode root) { StringBuilder sb=new StringBuilder(); if(root==null) return "#,"; sb.append(root.val+","); sb.append(Serialize(root.left)); sb.append(Serialize(root.right)); return sb.toString(); } TreeNode Deserialize(String str) { if(str==null) return null;
index=-1;
String[] ss=str.split(","); return DeserializeStr(ss); } public TreeNode DeserializeStr(String[] ss){ index++; TreeNode node=null; if(!ss[index].equals("#")){ node=new TreeNode(Integer.valueOf(ss[index])); node.left=DeserializeStr(ss); node.right=DeserializeStr(ss); }
return node; } } |