/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassCodec {
// Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null) return"[]"; StringBuildersb=newStringBuilder(); sb.append("["); Queue<TreeNode> queue = newLinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNodet= queue.poll(); if (t != null) { sb.append(t.val + ","); queue.add(t.left); queue.add(t.right); } else { sb.append("null,"); } } sb.deleteCharAt(sb.length() - 1); // 删除最后一个逗号 sb.append("]"); return sb.toString(); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data) { TreeNoderoot=null; if (data == null || data.equals("[]")) return root; String[] vals = data.substring(1, data.length() - 1).split(","); root = newTreeNode(Integer.parseInt(vals[0])); Queue<TreeNode> queue = newLinkedList<>(); queue.add(root); inti=1; while (!queue.isEmpty()) { TreeNodet= queue.poll(); //还原左子树 if (!vals[i].equals("null")) { t.left = newTreeNode(Integer.parseInt(vals[i])); queue.add(t.left); } i++; //还原右子树 if (!vals[i].equals("null")) { t.right = newTreeNode(Integer.parseInt(vals[i])); queue.add(t.right); } i++; }
return root; }
}
// Your Codec object will be instantiated and called as such: // Codec ser = new Codec(); // Codec deser = new Codec(); // TreeNode ans = deser.deserialize(ser.serialize(root));