当前位置:网站首页>Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树
Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树
2022-07-28 05:26:00 【JETECHO】
原题链接(https://leetcode.cn/problems/h54YBf/)
题目描述
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
示例1

输入:root = [1,2,3,null,null,4,5]
输出:[1,2,3,null,null,4,5]
示例2
输入:root = []
输出:[]
示例3
输入:root = [1]
输出:[1]
示例4
输入:root = [1,2]
输出:[1,2]
数据约束
- 树中结点数在范围 [0, 104] 内
- -1000 <= Node.val <= 1000
思路
对于将二叉树序列化最自然想到的就是二叉树的哪几种遍历方式了——先序遍历,中序遍历,后序遍历,这里采用先序遍历构建一个字符串,对于每一个节点将其对应的数字加入到其中,同时使用"null"填充二叉树使得二叉树成为一个“满二叉树”,在构造时使用String的split函数将其分解为字符数组,然后再用队列存储每个节点,每次都让一个节点出队,遇到为"null"的节点自然就给那个节点null即可。
如示例1将会变为
代码
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Codec {
public String serialize(TreeNode root) {
return serialize(root, "");
}
public String serialize(TreeNode root, String str) {
if (root == null) {
str += "null,";
} else {
String tmp = root.val + ",";
str += tmp;
str = serialize(root.left, str);
str = serialize(root.right, str);
}
return str;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] nodes=data.split(",");
Queue<String> queue=new LinkedList<>(Arrays.asList(nodes));
return deserialize(queue);
}
public TreeNode deserialize(Queue<String> queue) {
String val=queue.poll();
if(val.equals("null")) {
return null;
}
TreeNode node=new TreeNode(Integer.parseInt(val));
node.left=deserialize(queue);
node.right=deserialize(queue);
return node;
}
}
边栏推荐
猜你喜欢

2022-06-07 ResponseBodyAdvice导致Swagger出现弹框问题

Listener

Explain the installation of MSDN 2015 and precautions

使用wampserver3.2.6时切换中文时造成启动失败

What's a good gift for your girlfriend on Chinese Valentine's day? Boys who can't give gifts, look!

七夕礼物送女生什么好?颜值在线又有心意的礼物推荐
![[server usage record] log in to the remote server through the springboard machine and transfer files](/img/11/1ca6c2f34d43dfb6d766ec0dc3371d.png)
[server usage record] log in to the remote server through the springboard machine and transfer files

小程序自定义组件-数据,方法和属性

小程序:生命周期

多个ics日历合并成单个ics日历
随机推荐
【C语言】自定义结构体类型
刷题记录----反转链表(反转整个链表)
转义字符笔记
Several methods of QT setting loading interface
Common table expression CTE in Clickhouse
刷题记录----二叉树
QT parse string into JSON data and parse
Perl Introduction (10) formatted output
Introduction to Perl (IX) quotation
Icc2 (IV) routing and postroute optimization
【C语言】字符串库函数介绍及模拟
Get the current directory in QT
Pytorch learning notes 1 - quick start
QT custom sliding button (beautiful and easy to use)
气传导耳机哪个好、性价比最高的气传导耳机推荐
Ship detection in SAR image based on yolov5
JSP实现文件上传功能的同时还要向后台传递参数
我的注解笔记
Pytorch learning notes
Listener