二叉树序列化:可以用先中后序遍历的方式,将每一个节点中的信息保存为一个字符串,每一个节点的信息用特殊的符号作为分隔,如果所遍历到的节点为空(NULL)也要将其用特殊的符号表示为字符串。
反序列化:用什么方式序列化的就用什么方式还原。
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class TreeNode {
public static class Node {
private String number;
private Node leftNode;
private Node rightNode;
public Node(String number, Node leftNode, Node rightNode) {
this.number = number;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
}
public static void creadNodeNode() {
Node Node7 = new Node("7", null, null);
Node Node6 = new Node("6", null, null);
Node Node5 = new Node("5", null, null);
Node Node4 = new Node("4", null, null);
Node Node3 = new Node("3", Node6, Node7);
Node Node2 = new Node("2", Node4, Node5);
Node Node1 = new Node("1", Node2, Node3);
fileObject(Node1);
}
public static String getNodeStr(Node node) {
if (null == node) {
return null;
}
Node poin = node;
Stack<Node> stack = new Stack<>();
String str = "";
while (null != poin || !stack.isEmpty()) {
if (null != poin) {
stack.push(poin);
poin = poin.leftNode;
if (null == poin) {
stack.push(new Node(null, null, null));
}
} else {
Node pop = stack.pop();
String number = pop.number;
if (null == number) {
str += "#" + " ";
} else {
str += number + " ";
}
poin = pop.rightNode;
if (null != number && null == poin) {
stack.push(new Node(null, null, null));
}
}
}
return str;
}
public static void fileObject(Node node) {
Queue<String> priorityQueue = new LinkedList<>();
String nodeStr = getNodeStr(node);
String[] s = nodeStr.split(" ");
for (int i = 1; i < s.length; i++) {
priorityQueue.offer(s[i]);
}
Node createNode = getCreateNode(priorityQueue);
prTreeNode(createNode);
}
public static void prTreeNode(Node node){
if(null== node){
return;
}
System.out.println(node.number); //先序遍历
prTreeNode(node.leftNode);
//System.out.println(node.number); 中序遍历
prTreeNode(node.rightNode);
//System.out.println(node.number);后序遍历
}
public static Node getCreateNode(Queue<String> priorityQueue) {
if(priorityQueue.size()==0 || null== priorityQueue){
return null;
}
String poll = priorityQueue.poll();
if(poll .equals("#") ){
return null;
}
Node left = getCreateNode(priorityQueue);
Node head = new Node(poll, null, null);
Node right = getCreateNode(priorityQueue);
head.leftNode = left;
head.rightNode = right;
return head;
}
public static void main(String[] args) {
creadNodeNode();
}
}
|