来自左神书中的一道题,在左神核心代码的基础上,添加了二叉树的构建和前序遍历操作,将这道题完善成了一个小Demo,和各位共勉。
题目:
二叉树的序列化和反序列化。
名词解释:
* 二叉树的序列化:二叉树被记录成文件
* 二叉树的反序列化:通过文件重建二叉树
我们通过先序遍历实现序列化,假设序列化的结果字符串为str,初识为"",先序遍历二叉树,如果遇到null节点就在str末尾加上"#!","#"表示这个节点为空, "!"表示一个值的结束,如果节点值为x,就在str末尾加上"3!"。
我们测试的二叉树如下:
* 二叉树:
* 1
* 2 3
* 4 5 6 7
* 8 9
先序遍历序列化结果:1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!
逆序列化反之即可。
核心算法:
序列化:
public static String serialByPre(Node head){
if(head == null){
return "#!";
}
String s = head.data + "!";
s += serialByPre(head.leftChild);
s += serialByPre(head.rightChild);
return s;
}
反序列化:
public static Node reconByPreString(String preStr){
String values[] = preStr.split("!");
Queue<String> queue = new LinkedList<String>();
for(int i = 0;i < values.length;i++){
queue.offer(values[i]);
}
return reconPreOrder(queue);
}
public static Node reconPreOrder(Queue<String> queue) {
String value = queue.poll();
if(value.equals("#")){
return null;
}
Node head = new Node(Integer.valueOf(value));
head.leftChild = reconPreOrder(queue);
head.rightChild = reconPreOrder(queue);
return head;
}
先序遍历:
public static void preOrderTraverse(Node node) {
if (node == null)
return;
System.out.print(node.data + " ");
preOrderTraverse(node.leftChild);
preOrderTraverse(node.rightChild);
}
测试代码:
二叉树的构建:
public void createBinTree() {
// 将一个数组的值依次转换为Node节点
for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {
nodeList.add(new Node(array[nodeIndex]));
}
// 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
// 左孩子
nodeList.get(parentIndex).leftChild = nodeList
.get(parentIndex * 2 + 1);
// 右孩子
nodeList.get(parentIndex).rightChild = nodeList
.get(parentIndex * 2 + 2);
}
// 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
int lastParentIndex = array.length / 2 - 1;
// 左孩子
nodeList.get(lastParentIndex).leftChild = nodeList
.get(lastParentIndex * 2 + 1);
// 右孩子,如果数组的长度为奇数才建立右孩子
if (array.length % 2 == 1) {
nodeList.get(lastParentIndex).rightChild = nodeList
.get(lastParentIndex * 2 + 2);
}
}
main方法:
private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private static List<Node> nodeList = new LinkedList<Node>();;
public static void main(String[] args) {
SerialAndReconTest binTree = new SerialAndReconTest();
binTree.createBinTree();
/*
* 二叉树:
* 1
* 2 3
* 4 5 6 7
* 8 9
*/
// nodeList中第0个索引处的值即为根节点
Node root = nodeList.get(0);
System.out.println(serialByPre(root));
//1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!
// String preStr = "1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!";
// Node root = reconByPreString(preStr);
// preOrderTraverse(root);
}
输出结果:
1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!
1 2 4 8 9 5 3 6 7
原创不易,转载请注明出处哈。
权兴权意
http://blog.csdn.net/hxqneuq2012/article/details/53290522