import java.util.LinkedList;
import java.util.Queue;
/**
* @author Lei
* @date 2024/1/20
*/
public class SerializeAndReconstructTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
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 Node reconByPreString(String preStr) {
String[] values = preStr.split("!");
Queue<String> queue = new LinkedList<>();
for (String value : values) {
queue.offer(value);
}
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.left = reconPreOrder(queue);
head.right = reconPreOrder(queue);
return head;
}
public static String serialByLevel(Node head) {
if (head == null) {
return null;
}
StringBuilder res = new StringBuilder(head.value + "!");
Queue<Node> queue = new LinkedList<>();
queue.offer(head);
while (!queue.isEmpty()) {
head = queue.poll();
if (head.left != null) {
res.append(head.left.value).append("!");
queue.offer(head.left);
}else {
res.append("#!");
}
if (head.right != null) {
res.append(head.right.value).append("!");
queue.offer(head.right);
}else {
res.append("#!");
}
}
return res.toString();
}
public static Node reconByLevelString(String levelStr) {
String[] values = levelStr.split("!");
int index = 0;
Node head = generateNodeByString(values[index++]);
Queue<Node> list = new LinkedList<>();
if (head != null) {
list.offer(head);
}
Node node = null;
while (!list.isEmpty()) {
node = list.poll();
node.left = generateNodeByString(values[index++]);
node.right = generateNodeByString(values[index++]);
if (node.left != null) {
list.offer(node.left);
}
if (node.right != null) {
list.offer(node.right);
}
}
return head;
}
public static Node generateNodeByString(String val) {
if (val.equals("#")) {
return null;
}
return new Node(Integer.valueOf(val));
}
}
二叉树序列化
最新推荐文章于 2024-08-23 15:54:50 发布