《程式設計師程式碼面試指南》二叉樹的序列化和反序列化——java實現
阿新 • • 發佈:2018-12-17
二叉樹的序列化和反序列化
題目描述:
二叉樹被記錄成檔案的過程叫作二叉樹的序列化,通過檔案內容重建原來二叉樹的過程叫作二叉樹的反序列化。 給定一棵二叉樹的頭節點head,並已知二叉樹節點值的型別為32位整型。請設計一種二叉樹序列化和反序列化的方案,並用程式碼實現。 【要求】 1,實現先序遍歷序列化與反序列化 2,實現按層遍歷序列化與反序列化
題目難度:
題目思路:
1、先序遍歷序列化,即採用遞迴的方式,如果遇到null,則拼接“#”,反之則拼接“”。 2、反序列化,先採用字串分割,將每個字串新增到佇列中;採用遞迴的方式,分別找到頭結點及左右孩子節點。
程式碼實現:
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
//先序遍歷序列化
public static String serialByPre(Node head){
if (head == null){
return "#_";
}
String res = head.value +"_";
res += serialByPre(head.left);
res += serialByPre(head.right);
return res;
}
//先序遍歷反序列化
public static Node reconByPreString(String preStr){
String[] vlaue = preStr.split("_");
Queue<String> queue = new LinkedList <>();
for (String str : vlaue){
queue.offer(str);
}
return reconPreOrder(queue);
}
private static Node reconPreOrder(Queue<String> queue) {
String value = queue.poll();
if (value.equals("#")){
return null;
}
Node head = new Node(Integer.valueOf(value));
head.left = reconPreOrder(queue);
head.right = reconPreOrder(queue);
return head;
}