牛客(61)序列化二叉树
// 题目描述 // 请实现两个函数,分别用来序列化和反序列化二叉树 public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } String Serialize(TreeNode root) { StringBuilder stringBuilder = new StringBuilder(); doSerialize(root,stringBuilder); return stringBuilder.toString(); } public void doSerialize(TreeNode root,StringBuilder stringBuilder){ if (root==null){ stringBuilder.append("#,"); return; } stringBuilder.append(root.val); stringBuilder.append(","); doSerialize(root.left,stringBuilder); doSerialize(root.right,stringBuilder); } TreeNode Deserialize(String str) { if (str==null){ return null; } String[] strings = str.split(","); return doDeserialize(strings); } int index = -1; public TreeNode doDeserialize(String[] str){ index ++; if (!str[index].equals("#")){ TreeNode node = new TreeNode(Integer.valueOf(str[index])); node.left = doDeserialize(str); node.right= doDeserialize(str); return node; } return null; }