import java.util.Queue;
public class serialize {
public class Node {
public int value;
public Node left;
public Node right;
Node(int data) { value = data; }
}
public static String serialBypre(
Node head) { //此函数采用先序遍历将所有节点的值转化为需要转化的符号
if (head = null)
return "#!";
String res = head.value + "!";
res += serialize(head.left);
res += serialize(head.right);
return res;
}
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 reconByPreOrder(queue);
}
public static Node reconByPreOrder(Queue<String> queue) {
String values = queue.poll();
if (values.equals("#")) {
return null;
}
Node head = new Node(Integer.valueOf(values));
head.left = reconByPreOrder(queue);
head.right = reconByPreOrder(queue);
return head;
}
}
将二叉树序列化
最新推荐文章于 2024-09-11 00:16:09 发布
该博客介绍了如何使用Java实现二叉树的先序遍历序列化和反序列化。`serialize`方法通过先序遍历将二叉树转换为字符串,而`reconByPreString`和`reconByPreOrder`则根据预序遍历字符串重建二叉树。这种方法对于存储和恢复二叉树数据结构非常有用。
摘要由CSDN通过智能技术生成