剑指Offer_61 发表于 2017-12-06 | 分类于 剑指Offer 题目请实现两个函数,分别用来序列化和反序列化二叉树 解题思路序列化二叉树: 前序遍历二叉树 反序列化二叉树: 根据“#” 的值判断是否应该构造节点 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { String Serialize(TreeNode root) { StringBuffer sb = new StringBuffer(); if(root == null){ sb.append("#,"); return sb.toString(); } sb.append(root.val + ","); sb.append(Serialize(root.left)); sb.append(Serialize(root.right)); return sb.toString(); } private int index; private TreeNode DeserializeHelper(String []strings){ ++index; TreeNode node = null; if(!strings[index].equals("#")){ node = new TreeNode(Integer.valueOf(strings[index])); node.left = DeserializeHelper(strings); node.right = DeserializeHelper(strings); } return node; } TreeNode Deserialize(String str) { index = -1; String []strings = str.split(","); return DeserializeHelper(strings); } }