LeetCode 297. Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化(C++/Java)
题目:
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Example:
- You may serialize the following tree:
- 1
- / \
- 2 3
- / \
- 4 5
- as
"[1,2,3,null,null,4,5]"
Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
分析:
给定一颗二叉树将其序列化,也就是转换成一个字符串,同时还需要有一个反序列化的函数用来将字符串还原成二叉树。
采用前序遍历或者层次遍历都可以,注意的是LeetCode上要求,不要使用类的成员 / 全局 / 静态变量来存储状态,你的序列化和反序列化算法应该是无状态的。
C++中可以将 string 对象作为流处理,也就是istringstream 和 ostringstream。
程序:
C++
- class Codec {
- public:
- // Encodes a tree to a single string.
- string serialize(TreeNode* root) {
- ostringstream out;
- serialize(root, out);
- return out.str();
- }
- void serialize(TreeNode* root, ostringstream& out){
- if(root != nullptr){
- out << root->val << ' ';
- serialize(root->left, out);
- serialize(root->right, out);
- }
- else{
- out << "# ";
- }
- }
- // Decodes your encoded data to tree.
- TreeNode* deserialize(string data) {
- istringstream in(data);
- return deserialize(in);
- }
- TreeNode* deserialize(istringstream& in){
- string val;
- in >> val;
- if(val == "#"){
- return nullptr;
- }
- TreeNode* root = new TreeNode(stoi(val));
- root->left = deserialize(in);
- root->right = deserialize(in);
- return root;
- }
- };
Java
- public class Codec {
- // Encodes a tree to a single string.
- public String serialize(TreeNode root) {
- if(root == null)
- return "";
- StringBuilder str = new StringBuilder();
- serialize(root, str);
- return str.toString();
- }
- public void serialize(TreeNode root, StringBuilder str){
- if(root == null){
- str.append("#,");
- return;
- }
- str.append(root.val + ",");
- serialize(root.left, str);
- serialize(root.right, str);
- }
- // Decodes your encoded data to tree.
- public TreeNode deserialize(String data) {
- if(data == "" || data == null)
- return null;
- String[] strs = data.split(",");
- LinkedList<String> l = new LinkedList<>(Arrays.asList(strs));
- return deserialize(l);
- }
- public TreeNode deserialize(LinkedList<String> list) {
- if(list.getFirst().equals("#")){
- list.removeFirst();
- return null;
- }
- TreeNode root = new TreeNode(Integer.parseInt(list.getFirst()));
- list.removeFirst();
- root.left = deserialize(list);
- root.right = deserialize(list);
- return root;
- }
- }
LeetCode 297. Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化(C++/Java)的更多相关文章
- [LeetCode] 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- 297 Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据.请设计一个算法来实现二叉树 ...
- 297. Serialize and Deserialize Binary Tree二叉树的序列化和反序列化(就用Q)
[抄题]: Serialization is the process of converting a data structure or object into a sequence of bits ...
- [leetcode]297. Serialize and Deserialize Binary Tree 序列化与反序列化二叉树
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- Leetcode 297. Serialize and Deserialize Binary Tree
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ Serialization is the process of ...
- [leetcode]297. Serialize and Deserialize Binary Tree一般二叉树的编解码
由于一般的前序遍历不能唯一的还原出原本你的二叉树,所以要改变一下: 记录二叉树的结构信息,也就是空节点用符号表示 一般的前序遍历只是记录了节点的前后顺序,通过记录空节点,每一层的结构就可以记录下来 解 ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
- LC 297 Serialize and Deserialize Binary Tree
问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree
二叉树的序列化与反序列化. 如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便. 这里学会了使用 sstream 中的 输入流'istringstream' 和 输出流 ...
随机推荐
- 剑指offer04(Java)二维数组中的查找(中等)
题目: 在一个 n * m 的二维数组中,每一行都按照从左到右 非递减 的顺序排序,每一列都按照从上到下 非递减 的顺序排序.请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有 ...
- python格式化时间报错:UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence
执行下列代码: from datetime import datetime t = datetime.now() print(t) print(t.strftime("%Y年%m月%d日,% ...
- 力扣383(java&python)-赎金信(简单)
题目: 给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成. 如果可以,返回 true :否则返回 false . m ...
- TiDB、OceanBase、PolarDB-X、CockroachDB二级索引写入性能测评
简介: 二级索引是关系型数据库相较于NoSQL数据库的一个关键差异.二级索引必须是强一致的,因此索引的写入需要与主键的写入放在一个事务当中,事务的性能是二级索引性能的基础.本次测试将重点关注不同分布式 ...
- 最佳实践丨云上虚拟IDC(私有池)如何为客户业务的确定性、连续性保驾护航
简介: 企业业务上云后,还面临特定可用区购买云上特定计算产品实例失败的困境?云上私有池pick一下 Why 云上业务为什么需要资源确定性.服务连续性 云计算正朝着像水电煤一样的基础设施演进,支持用户 ...
- [Trading] 什么是交易中的顺势和逆势
开仓后的头寸开始盈利了并不断增加,这就是顺势:开仓后的头寸没有盈利或者亏损了,这就是逆势. 开仓后,用你持有的头寸判断,有浮盈的头寸单子就是正确的. 盈利取决你处理单子的能力,而处理单子是从开仓以后开 ...
- [FAQ] swagger-php @OA\JsonContent 与 @MediaType @OA\Schema 的用法
@OA\JsonContent 是对 @MediaType @OA\Schema 两者的封装,类似于 laravel 中 JsonResponse 对 Response 的封装. @OA\JsonCo ...
- 《Effective C++》第三版-1. 让自己习惯C++(Accustoming Yourself to C++)
目录 条款01:视C++为一个语言联邦(View C++ as a federation of languages) 条款02:尽量以const.enum.inline替换#define(Prefer ...
- FFmpeg开发笔记(十九)FFmpeg开启两个线程分别解码音视频
同步播放音视频的时候,<FFmpeg开发实战:从零基础到短视频上线>一书第10章的示例程序playsync.c采取一边遍历一边播放的方式,在源文件的音频流和视频流交错读取的情况下,该方式 ...
- VMware最小化安装Centos7.6-无桌面
目录 安装包工具 新建虚拟机 安装 centos 7.6 系统 终端登陆系统 设置ip地址 关闭防火墙 关闭 SELINUX SELINUX=enforcing 硬盘挂载 桥接上网方式 安装包工具 V ...