当前位置:网站首页>20220529设计问题:二叉树的序列化与反序列化
20220529设计问题:二叉树的序列化与反序列化
2022-08-09 02:37:00 【丿SeeYouAgain】
题目描述:序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
编码实现:
private static final String TMP= "-",SEP= ",";
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
}
private void serialize(TreeNode root, StringBuilder sb) {
if (root == null){
sb.append(TMP).append(SEP);
return;
}
sb.append(root.val).append(SEP);
serialize(root.left, sb);
serialize(root.right, sb);
}
public TreeNode deserialize(String data) {
LinkedList<String> nodes = new LinkedList<>();
Collections.addAll(nodes, data.split(SEP));
return deserialize(nodes);
}
private TreeNode deserialize(LinkedList<String> nodes) {
if (nodes.isEmpty()){
return null;
}
String val = nodes.removeFirst();
if (TMP.equals(val)){
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(val));
root.left = deserialize(nodes);
root.right = deserialize(nodes);
return root;
}
边栏推荐
- 2.1-----27. Remove elements
- Likou Brush Question Record 1.5-----367. Valid perfect squares
- 2022 China Eye Expo, China Beijing International Children and Adolescent Eye Health Industry Exhibition
- 9.1-----24. Swap the nodes in the linked list in pairs
- gpio子系统和pinctrl子系统(中)
- [Redis] The core principle of master-slave replication
- Flume (四) --------- Flume 企业开发案例
- MT4/MQL4 Getting Started to Mastering EA Tutorial Lesson 1 - MQL Language Common Functions (1) OrderSend() Function
- 1261. 在受污染的二叉树中查找元素
- Line segment tree of knowledge
猜你喜欢
opencv在图像上长按左键画矩形单击右键清除
[Redis] The core principle of master-slave replication
使用TensorRT对AlphaPose模型进行加速
通过安装VNC服务器x11vnc(或vnc4server)和配置x11vnc.service实现远程通过VNC-Viewer访问VNC服务器。
OJ:L3-021 神坛 伪解 排序后遍历
2022年自然语言处理校招社招实习必备知识点盘点分享
概率模型校准
目标检测中mAP计算以及源码解析
SQLite切换日志模式优化
Financial Industry Software Testing Interview Questions (with Answers) | Getting Started Guide
随机推荐
接口自动化测试-接口封装思想
Jenkins配置钉钉通知
17.flink Table Api基础概念讲解
Cyclictest 简介 安装 测试
Open3D 均匀采样
What aspects should we start with for interface security testing?
A40i gxl3680 ts_print报错:tslib: Selected device is not a touchscreen (must support ABS and KEY event
The most fierce "employee" in history, madly complaining about the billionaire boss Xiao Zha: So rich, he always wears the same clothes!
笔算开2次方根、3次方根详细教程
DataGridView在多线程中出现大红叉
如何最大限度地减少企业受到供应链攻击的风险
Electromagnetic radiation safety standards and detection methods
Apache站点下载大文件自动中断或者文件不完整
使用TensorRT对AlphaPose模型进行加速
C#计算两个时间相差多少天、时、分、秒
Pytest+request+Allure实现接口自动化框架
313. 超级丑数-暴力解法
1261. 在受污染的二叉树中查找元素
攀爬倒影发光方块
独立机器连接cdh的spark集群,远程提交任务(绝对可以成功,亲测了n遍)