当前位置:网站首页>二叉树的序列化和反序列化
二叉树的序列化和反序列化
2022-08-09 12:00:00 【爱敲代码的Harrison】
- 可以用先序或者中序或者后序或者按层遍历,来实现二叉树的序列化
- 用了什么方式序列化,就用什么样的方式反序列化
- 但是,二叉树无法通过中序遍历的方式实现序列化和反序列化
- 所以,二叉树可以通过先序、后序或者按层遍历的方式序列化和反序列化,
- 不同的两棵树,可能得到同样的中序序列,即便补了空位置也可能一样。比如如下两棵树,补足空位置的中序遍历结果都是{ null, 1, null, 2, null}
// __2
// /
// 1
// 和
// 1__
// \
// 2
package com.harrison.class07;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/** * @author Harrison * @create 2022-03-09-14:58 * @motto 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。 */
public class Code04_SerializeAndReconstructBT {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int v){
value=v;
}
}
// 先序序列化
public static Queue<String> preSerial(Node head){
Queue<String> ans=new LinkedList<>();
pres(head,ans);
return ans;
}
public static void pres(Node head,Queue<String> ans){
if(head==null){
ans.add(null);
}else{
ans.add(String.valueOf(head.value));
pres(head.left,ans);
pres(head.right,ans);
}
}
// 先序重建
public static Node buildByPreQueue(Queue<String> preList){
if(preList==null || preList.size()==0){
return null;
}
return preb(preList);
}
public static Node preb(Queue<String> preList){
String value=preList.poll();
if(value==null){
return null;
}
Node head=new Node(Integer.valueOf(value));
head.left=preb(preList);
head.right=preb(preList);
return head;
}
// 后序序列化
public static Queue<String> posSerial(Node head){
Queue<String> ans=new LinkedList<>();
poss(head,ans);
return ans;
}
public static void poss(Node head,Queue<String> ans){
if(head==null){
ans.add(null);
}else{
poss(head.left,ans);
poss(head.right,ans);
ans.add(String.valueOf(head.value));
}
}
// 后序重建 左右根 -》 根右左
public static Node buildByPosQueue(Queue<String> posList){
if(posList==null || posList.size()==0){
return null;
}
Stack<String> stack=new Stack<>();
while(!posList.isEmpty()){
stack.push(posList.poll());
}
return posb(stack);
}
public static Node posb(Stack<String> posStack){
String value=posStack.pop();
if(value==null){
return null;
}
Node head=new Node(Integer.valueOf(value));
head.right=posb(posStack);
head.left=posb(posStack);
return head;
}
// 按层序列化
public static Queue<String> levelSerial(Node head){
Queue<String> ans=new LinkedList<>();
if(head==null){
ans.add(null);
}else{
ans.add(String.valueOf(head.value));
Queue<Node> queue=new LinkedList<>();
queue.add(head);
while(!queue.isEmpty()){
head=queue.poll();
if(head.left!=null){
ans.add(String.valueOf(head.left.value));
queue.add(head.left);
}else{
ans.add(null);
}
if(head.right!=null){
ans.add(String.valueOf(head.right.value));
queue.add(head.right);
}else{
ans.add(null);
}
}
}
return ans;
}
// 按层重建
public static Node buildByLevelQueue(Queue<String> levelList){
if(levelList==null || levelList.size()==0){
return null;
}
Queue<Node> queue=new LinkedList<>();
Node head=generateNode(levelList.poll());
if(head!=null){
queue.add(head);
}
Node node=null;
while(!queue.isEmpty()){
node=queue.poll();
node.left=generateNode(levelList.poll());
node.right=generateNode(levelList.poll());
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
return head;
}
public static Node generateNode(String value){
if(value==null){
return null;
}
return new Node(Integer.valueOf(value));
}
public static Node generate(int level,int maxLevel,int maxValue){
if(level>maxLevel || Math.random()<0.5){
return null;
}
Node head=new Node((int)(Math.random()*maxValue));
head.left=generate(level+1,maxLevel,maxValue);
head.right=generate(level+1,maxLevel,maxValue);
return head;
}
public static Node generateRandomBST(int maxLevel,int maxValue){
return generate(1,maxLevel,maxValue);
}
public static boolean isSameValueStructure(Node head1, Node head2) {
if (head1 == null && head2 != null) {
return false;
}
if (head1 != null && head2 == null) {
return false;
}
if (head1 == null && head2 == null) {
return true;
}
if (head1.value != head2.value) {
return false;
}
return isSameValueStructure(head1.left, head2.left) && isSameValueStructure(head1.right, head2.right);
}
public static void main(String[] args) {
int maxLevel = 5;
int maxValue = 100;
int testTimes = 1000000;
System.out.println("test begin");
for (int i = 0; i < testTimes; i++) {
Node head = generateRandomBST(maxLevel, maxValue);
Queue<String> pre = preSerial(head);
Queue<String> pos = posSerial(head);
Queue<String> level = levelSerial(head);
Node preBuild = buildByPreQueue(pre);
Node posBuild = buildByPosQueue(pos);
Node levelBuild = buildByLevelQueue(level);
if (!isSameValueStructure(preBuild, posBuild) || !isSameValueStructure(posBuild, levelBuild)) {
System.out.println("Oops!");
}
}
System.out.println("test finish!");
}
}
边栏推荐
- [Interview high-frequency questions] Linked list high-frequency questions that can be gradually optimized
- 二重指针-char **、int **的作用
- Shell之常用小工具(sort、uniq、tr、cut)
- 从零开始Blazor Server(9)--修改Layout
- 香港服务器如何进行加密?
- Information system project managers must memorize the core test sites (63) The main process of project portfolio management & DIPP analysis
- 推荐一个免费50时长的AI算力平台
- 已解决IndentationError: unindent does not match any oute r indentation Level
- 在北极都可以穿短袖了,温度飙升至32.5℃
- 报告:想学AI的学生数量已涨200%,老师都不够用了
猜你喜欢
西湖大学教授怎么看AI制药革命?|量子位智库圆桌实录
Here comes the question: Can I successfully apply for 8G memory on a machine with 4GB physical memory?
Byte Qiu Zhao confused me on both sides, and asked me under what circumstances would the SYN message be discarded?
【小程序】低代码+小游戏=小游戏可视化开发
win10编译x264库(也有生成好的lib文件)
微信一面:一致性哈希是什么,使用场景,解决了什么问题?
Programmer's Exclusive Romance - Use 3D Engine to Realize Fireworks in 5 Minutes
听声辨物,这是AI视觉该干的???|ECCV 2022
JD.com architects tidy up: what are the core technical knowledge points of jvm and performance tuning
信息系统项目管理师必背核心考点(六十三)项目组合管理的主要过程&DIPP分析
随机推荐
世界第4疯狂的科学家,在103岁生日那天去世了
1-hour live broadcast recruitment order: industry big names share dry goods, and enterprise registration opens丨qubit·viewpoint
goalng-sync/atomic原子操作
PM2 configuration file
The batch size does not have to be a power of 2!The latest conclusions of senior ML scholars
索引index
win10编译x264库(也有生成好的lib文件)
2022牛客多校(六)M. Z-Game on grid
Information system project managers must memorize the core test sites (63) The main process of project portfolio management & DIPP analysis
Modify the VOT2018.json file and remove the color in the image path
We really need DApp?Really can't meet our fantasy App?
字节秋招二面把我干懵了,问我SYN报文什么情况下会被丢弃?
软件测试——金融测试类面试题,看完直接去面试了
脱光衣服待着就能减肥,当真有这好事?
基于CAP组件实现补偿事务与幂等性保障
箭头函数和普通函数的常见区别
虚拟机安装出现的问题汇总
十分钟教会你如何使用VitePress搭建及部署个人博客站点
WPF implements a MessageBox message prompt box with a mask
LeetCode热题(11.合并两个有序链表)