【剑指Offer】序列化二叉树 Posted on 2017-09-08 | In Algorithm , 剑指Offer 题目请实现两个函数,分别用来序列化和反序列化二叉树。 实现123456789public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }} 1234567891011121314151617181920212223242526272829303132333435363738private int idx = -1;public String Serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); if (root == null) { sb.append("$,"); return sb.toString(); } sb.append(root.val).append(","); sb.append(Serialize(root.left)); sb.append(Serialize(root.right)); return sb.toString();}public TreeNode Deserialize(String str) { if (str == null || str.length() < 1) return null; String[] strs = str.split(","); return Deserialize(strs);}private TreeNode Deserialize(String[] strs) { idx++; TreeNode root = null; if (idx < strs.length && !strs[idx].equals("$")) { root = new TreeNode(Integer.valueOf(strs[idx])); root.left = Deserialize(strs); root.right = Deserialize(strs); } return root;}