public class SerialByPre { //序列化代码 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 void main(String[] args) { // TODO Auto-generated method stub Node head = new Node(1); head.left = new Node(2); head.right = new Node(3); head.left.left = new Node(4); head.left.right= new Node(5); head.right.left= new Node(6); head.right.right= new Node(7); String str = serialByPre(head); System.out.println(str); } }
反序列化: 反序列化函数:
1 2 3 4 5 6 7 8
public static Node reconByPreString (String preStr) { String[] strs = preStr.split("_"); Queue<String> queue = new LinkedList<String>(); for (int i = 0; i < strs.length; i++) { queue.offer(strs[i]); } return reconPreOrder(queue); }
reconPreNode函数: 作用是从一个字符串重构出一棵二叉树
1 2 3 4 5 6 7 8 9 10
public static Node reconPreNode(Queue<String> queue) { String value = queue.poll(); if (value.equals("#")) { return null; } Node head = new Node(Integer.valueOf(value)); head.left = reconPreNode(queue); head.right = reconPreNode(queue); return head; }