package class07;
import java.util.*;
public class SerialBT {
public static class Node{
int value;
Node left;
Node right;
public Node(int value){
this.value=value;
}
}
public static void SerialByPre(Node head){
Queue<String> queue=new LinkedList<>();
preSerial(head,queue);
}
public static void preSerial(Node head,Queue<String> queue){
if(head==null){
queue.add(null);
}else{
queue.add(String.valueOf(head.value));
preSerial(head.left,queue);
preSerial(head.right,queue);
}
}
public static void inSerial(Node head,Queue<String> queue){
if(head==null) queue.add(null);
else{
inSerial(head.left,queue);
queue.add(String.valueOf(head.value));
inSerial(head.right,queue);
}
}
public static void posSerial(Node head,Queue<String> queue){
if(head==null) queue.add(null);
else{
inSerial(head.left,queue);
inSerial(head.right,queue);
queue.add(String.valueOf(head.value));
}
}
public static Node unPreSerial(Queue<String> queue){
String value = queue.poll();
if(value==null) return null;
Node head=new Node(Integer.valueOf(value));
head.left= unPreSerial(queue);
head.right=unPreSerial(queue);
return head;
}
public static void unPosSerial(Queue<String> queue){
String value = queue.poll();
if(value==null) return;
Stack<String> stack=new Stack<>();
stack.push(value);
while(!queue.isEmpty()){
stack.push(queue.poll());
}
}
public static Node unPosSerial(Stack<String> stack){
String value=stack.pop();
if(value==null) return null;
else{
Node head=new Node(Integer.valueOf(value));
head.left=unPosSerial(stack);
head.right=unPosSerial(stack);
return head;
}
}
public static void levelSerial(Node head){
Queue<String> data=new LinkedList<>();
if(head==null) {
data.offer(null);
return;
} else {
Queue<Node> queue = new LinkedList<>();
queue.offer(head);
data.offer(String.valueOf(head.value));
while (!queue.isEmpty()) {
head = queue.poll();
if (head.left != null) {
queue.offer(head.left);
data.offer(String.valueOf(head.left));
} else {
data.offer(null);
}
if (head.right != null) {
queue.offer(head.right);
data.offer(String.valueOf(head.right));
} else {
data.offer(null);
}
}
}
}
public static Node unLevel(Queue<String> data){
String value = data.poll();
if(value==null){
return null;
}else{
Queue<Node> queue=new LinkedList<>();
Node head = Generate(value);
queue.add(head);
while(!queue.isEmpty()){
Node cur = queue.poll();
cur.left=Generate(data.poll());
cur.right=Generate(data.poll());
if(cur.left!=null) queue.add(cur.left);
if(cur.right!=null) queue.add(cur.right);
}
return head;
}
}
public static Node Generate(String value){
if(value==null) return null;
else{
return new Node(Integer.valueOf(value));
}
}
}