题目:

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:

  1. You may serialize the following tree:
  2.  
  3. 1
  4. / \
  5. 2 3
  6. / \
  7. 4 5
  8.  
  9. 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++

  1. class Codec {
  2. public:
  3.  
  4. // Encodes a tree to a single string.
  5. string serialize(TreeNode* root) {
  6. ostringstream out;
  7. serialize(root, out);
  8. return out.str();
  9. }
  10. void serialize(TreeNode* root, ostringstream& out){
  11. if(root != nullptr){
  12. out << root->val << ' ';
  13. serialize(root->left, out);
  14. serialize(root->right, out);
  15. }
  16. else{
  17. out << "# ";
  18. }
  19. }
  20. // Decodes your encoded data to tree.
  21. TreeNode* deserialize(string data) {
  22. istringstream in(data);
  23. return deserialize(in);
  24. }
  25. TreeNode* deserialize(istringstream& in){
  26. string val;
  27. in >> val;
  28. if(val == "#"){
  29. return nullptr;
  30. }
  31. TreeNode* root = new TreeNode(stoi(val));
  32. root->left = deserialize(in);
  33. root->right = deserialize(in);
  34. return root;
  35. }
  36. };

Java

  1. public class Codec {
  2.  
  3. // Encodes a tree to a single string.
  4. public String serialize(TreeNode root) {
  5. if(root == null)
  6. return "";
  7. StringBuilder str = new StringBuilder();
  8. serialize(root, str);
  9. return str.toString();
  10. }
  11. public void serialize(TreeNode root, StringBuilder str){
  12. if(root == null){
  13. str.append("#,");
  14. return;
  15. }
  16. str.append(root.val + ",");
  17. serialize(root.left, str);
  18. serialize(root.right, str);
  19. }
  20.  
  21. // Decodes your encoded data to tree.
  22. public TreeNode deserialize(String data) {
  23. if(data == "" || data == null)
  24. return null;
  25. String[] strs = data.split(",");
  26. LinkedList<String> l = new LinkedList<>(Arrays.asList(strs));
  27. return deserialize(l);
  28. }
  29. public TreeNode deserialize(LinkedList<String> list) {
  30. if(list.getFirst().equals("#")){
  31. list.removeFirst();
  32. return null;
  33. }
  34. TreeNode root = new TreeNode(Integer.parseInt(list.getFirst()));
  35. list.removeFirst();
  36. root.left = deserialize(list);
  37. root.right = deserialize(list);
  38. return root;
  39. }
  40.  
  41. }

LeetCode 297. Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化(C++/Java)的更多相关文章

  1. [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 ...

  2. 297 Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化

    序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据.请设计一个算法来实现二叉树 ...

  3. 297. Serialize and Deserialize Binary Tree二叉树的序列化和反序列化(就用Q)

    [抄题]: Serialization is the process of converting a data structure or object into a sequence of bits ...

  4. [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 ...

  5. [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  6. Leetcode 297. Serialize and Deserialize Binary Tree

    https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ Serialization is the process of ...

  7. [leetcode]297. Serialize and Deserialize Binary Tree一般二叉树的编解码

    由于一般的前序遍历不能唯一的还原出原本你的二叉树,所以要改变一下: 记录二叉树的结构信息,也就是空节点用符号表示 一般的前序遍历只是记录了节点的前后顺序,通过记录空节点,每一层的结构就可以记录下来 解 ...

  8. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  9. LC 297 Serialize and Deserialize Binary Tree

    问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...

  10. 【LeetCode】297. Serialize and Deserialize Binary Tree

    二叉树的序列化与反序列化. 如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便. 这里学会了使用 sstream 中的 输入流'istringstream' 和 输出流 ...

随机推荐

  1. 剑指offer04(Java)二维数组中的查找(中等)

    题目: 在一个 n * m 的二维数组中,每一行都按照从左到右 非递减 的顺序排序,每一列都按照从上到下 非递减 的顺序排序.请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有 ...

  2. 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日,% ...

  3. 力扣383(java&python)-赎金信(简单)

    题目: 给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成. 如果可以,返回 true :否则返回 false . m ...

  4. TiDB、OceanBase、PolarDB-X、CockroachDB二级索引写入性能测评

    简介: 二级索引是关系型数据库相较于NoSQL数据库的一个关键差异.二级索引必须是强一致的,因此索引的写入需要与主键的写入放在一个事务当中,事务的性能是二级索引性能的基础.本次测试将重点关注不同分布式 ...

  5. 最佳实践丨云上虚拟IDC(私有池)如何为客户业务的确定性、连续性保驾护航

    ​简介: 企业业务上云后,还面临特定可用区购买云上特定计算产品实例失败的困境?云上私有池pick一下 Why 云上业务为什么需要资源确定性.服务连续性 云计算正朝着像水电煤一样的基础设施演进,支持用户 ...

  6. [Trading] 什么是交易中的顺势和逆势

    开仓后的头寸开始盈利了并不断增加,这就是顺势:开仓后的头寸没有盈利或者亏损了,这就是逆势. 开仓后,用你持有的头寸判断,有浮盈的头寸单子就是正确的. 盈利取决你处理单子的能力,而处理单子是从开仓以后开 ...

  7. [FAQ] swagger-php @OA\JsonContent 与 @MediaType @OA\Schema 的用法

    @OA\JsonContent 是对 @MediaType @OA\Schema 两者的封装,类似于 laravel 中 JsonResponse 对 Response 的封装. @OA\JsonCo ...

  8. 《Effective C++》第三版-1. 让自己习惯C++(Accustoming Yourself to C++)

    目录 条款01:视C++为一个语言联邦(View C++ as a federation of languages) 条款02:尽量以const.enum.inline替换#define(Prefer ...

  9. FFmpeg开发笔记(十九)FFmpeg开启两个线程分别解码音视频

    ​同步播放音视频的时候,<FFmpeg开发实战:从零基础到短视频上线>一书第10章的示例程序playsync.c采取一边遍历一边播放的方式,在源文件的音频流和视频流交错读取的情况下,该方式 ...

  10. VMware最小化安装Centos7.6-无桌面

    目录 安装包工具 新建虚拟机 安装 centos 7.6 系统 终端登陆系统 设置ip地址 关闭防火墙 关闭 SELINUX SELINUX=enforcing 硬盘挂载 桥接上网方式 安装包工具 V ...