剑指 Offer 37. 序列化二叉树
题目:
思路:
自定义序列化方式,采用先序遍历的房子,如果节点为null则置为一个字符,这样一个序列就搞定了,不像一个先序+中序进行恢复二叉树(而且不能有重复数据)
1.序列化,定义了一个全局变量,作为返回
2.反序列化,使用数组
定义全局变量就跟昨天说的引用传递一样,以后还是尽量避免这种类C++的写法。最后改成了ddfs,返回TreeNode。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private String s = "";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return null;
}
dfs(root);
return s;
}
private void dfs(TreeNode root) {
if (root == null) {
s += "@";
s += ",";
return;
}
s += root.val;
s += ",";
dfs(root.left);
dfs(root.right);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null) {
return null;
}
String[] strings = data.split(",");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
return ddfs(list);
}
private TreeNode ddfs(ArrayList<String> list) {
if (list.isEmpty()) {
return null;
}
String string = String.valueOf(list.get(0));
list.remove(0);
if (string.equals("@")) {
return null;
}
TreeNode treeNode = new TreeNode(Integer.valueOf(string));
treeNode.left = ddfs(list);
treeNode.right = ddfs(list);
return treeNode;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
不使用全局变量,修改后:
public class Codec {
// Encodes a tree to a single string.
public static String serialize(TreeNode root) {
if (root == null) {
return null;
}
String s = "";
s = dfs(root, s);
return s;
}
private static String dfs(TreeNode root, String s) {
if (root == null) {
s = s + "@" + ",";
return s;
}
s = s + root.val + ",";
s = dfs(root.left, s);
s = dfs(root.right, s);
return s;
}
// Decodes your encoded data to tree.
public static TreeNode deserialize(String data) {
if (data == null) {
return null;
}
String[] strings = data.split(",");
LinkedList<String> list = new LinkedList<>(Arrays.asList(strings));
return ddfs(list);
}
private static TreeNode ddfs(LinkedList<String> list) {
if (list.isEmpty()) {
return null;
}
String string = String.valueOf(list.get(0));
list.removeFirst();
if (string.equals("@")) {
return null;
}
TreeNode treeNode = new TreeNode(Integer.valueOf(string));
treeNode.left = ddfs(list);
treeNode.right = ddfs(list);
return treeNode;
}
}