LeetCode刷题记164
297. 二叉树的序列化与反序列化
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null) return "null";
String s = "";
Map<TreeNode, Integer> map = new HashMap<TreeNode, Integer>();
Stack<TreeNode> sta_dlr = new Stack<TreeNode>();
Set<TreeNode> set = new HashSet<TreeNode>();
sta_dlr.push(root);
int id = 0;
while(!sta_dlr.isEmpty()) {
TreeNode tmp = sta_dlr.peek();
if (!set.contains(tmp)) {
s += tmp.val + ":" + id + ",";
set.add(tmp);
map.put(tmp, id ++);
}
if (tmp.left != null && !set.contains(tmp.left)) {
sta_dlr.push(tmp.left);
} else if (tmp.right != null && !set.contains(tmp.right)) {
sta_dlr.push(tmp.right);
} else sta_dlr.pop();
}
Stack<TreeNode> sta = new Stack<TreeNode>();
sta.push(root);
set.clear();
while(!sta.isEmpty()) {
TreeNode tmp = sta.peek();
if (tmp.left != null && !set.contains(tmp.left)) {
sta.push(tmp.left);
set.add(tmp.left);
} else {
s += tmp.val + ":" + map.get(tmp) + ",";
sta.pop();
if (tmp.right != null) sta.push(tmp.right);
}
}
return s;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.compareTo("null") == 0) return null;
String[] datas= data.split(",");
int[] dlr = new int[datas.length / 2];
int[] dlr_id = new int[datas.length / 2];
int[] ldr = new int[datas.length / 2];
int[] ldr_id = new int[datas.length / 2];
for (int i = 0; i < datas.length/2; i ++) {
String[] tmp = datas[i].split(":");
dlr[i] = Integer.valueOf(tmp[0]);
dlr_id[i] = Integer.valueOf(tmp[1]);
}
for (int i = datas.length / 2; i < datas.length; i ++) {
String[] tmp = datas[i].split(":");
ldr[i - datas.length / 2] = Integer.valueOf(tmp[0]);
ldr_id[i - datas.length / 2] = Integer.valueOf(tmp[1]);
}
return build(dlr, ldr, dlr_id, ldr_id, 0, datas.length / 2 - 1, 0, datas.length / 2 - 1);
}
public TreeNode build(int[] dlr, int[] ldr, int[] dlr_id, int[] ldr_id, int pl, int pr, int il, int ir) {
if (pl > pr) return null;
int i = il;
for (; i <= ir; i ++) {
if (ldr[i] == dlr[pl] && ldr_id[i] == dlr_id[pl]) break;
}
TreeNode root = new TreeNode(dlr[pl]);
root.left = build(dlr, ldr, dlr_id, ldr_id, pl + 1, pl + i - il, il, i - 1);
root.right = build(dlr, ldr, dlr_id, ldr_id, pl + i - il + 1, pr, i + 1, ir);
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));
用了先序遍历和中序遍历,再还原,结果发现数据又重复的,这样还原的二叉树就有可能不是原来的,只能加上一个编号。
效率很低下,但是我不想做了。。