import java.util.LinkedList;
import java.util.Queue;

/**
* 序列化和反序列化二叉树
* 先序、后序
* (中序不能实现)
* 按层
*/
public class SerializeAndReconstructTree {

/**
* 先序序列化
*
* @param head 头结点
* @return 序列化结果
*/
public Queue<String> preSerialize(Node head) {
Queue<String> queue = new LinkedList<>();
pres(head, queue);
return queue;
}

private void pres(Node head, Queue<String> queue) {
if (head == null) {
queue.add(null);
} else {
queue.add(String.valueOf(head.value));
pres(head.left, queue);
pres(head.right, queue);
}
}

/**
* 先序反序列化
*
* @param queue 序列化队列
* @return 二叉树
*/
public Node buildByPreQueue(Queue<String> queue) {
if (queue == null || queue.isEmpty()) {
return null;
}
return preb(queue);
}

private Node preb(Queue<String> queue) {
String value = queue.poll();
if (value == null) {
return null;
}
Node head = new Node(Integer.parseInt(value));
head.left = preb(queue);
head.right = preb(queue);
return head;
}

/**
* 按层序列化
*/
public Queue<String> levelSerialize(Node head) {
Queue<String> result = new LinkedList<>();
if (head == null) {
result.add(null);
return result;
}
result.add(String.valueOf(head.value));
Queue<Node> queue = new LinkedList<>();
queue.add(head);
while (!queue.isEmpty()) {
Node node = queue.poll();
if (node.left != null) {
result.add(String.valueOf(node.left.value));
queue.add(node.left);
} else {
result.add(null);
}
if (node.right != null) {
result.add(String.valueOf(node.right.value));
queue.add(node.right);
} else {
result.add(null);
}
}
return result;
}

/**
* 按层反序列化
*/
public Node levelBuild(Queue<String> levelList) {
if (levelList == null || levelList.isEmpty()) {
return null;
}
Node head = generateNode(levelList.poll());
Queue<Node> queue = new LinkedList<>();
if (head != null) {
queue.add(head);
}
Node node = null;
while (!queue.isEmpty()) {
node = queue.poll();
node.left = generateNode(levelList.poll());
if (node.left != null) {
queue.add(node.left);
}
node.right = generateNode(levelList.poll());
if (node.right != null) {
queue.add(node.right);
}
}
return head;
}

private Node generateNode(String value) {
if (value == null) {
return null;
}
return new Node(Integer.parseInt(value));
}

/**
* 二叉树结构
*/
public class Node {

public int value;

public Node left;

public Node right;

public Node(int value) {
this.value = value;
}

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */