leetcode 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化 + 深度优先遍历DFS

骑猪看日落 2022-06-08 14:37 225阅读 0赞

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.

For example, you may serialize the following tree

1
/ \
2 3
/ \
4 5
as “[1,2,3,null,null,4,5]”, just the same as how LeetCode OJ 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.

题意很简答,就是完成二叉树的序列化和反序列化,序列化很容易错,也就是二叉树的遍历;对于反序列化,也就是把一个字符串转化为一个二叉树,这个还是用同样的思想去做,看了网上的一个答案,才明白原来是这么的简单。

先序遍历的递归解法和层序遍历的非递归解法。先来看先序遍历的递归解法,非常的简单易懂,我们需要接入输入和输出字符串流istringstream和ostringstream,对于序列化,我们从根节点开始,如果节点存在,则将值存入输出字符串流,然后分别对其左右子节点递归调用序列化函数即可。对于去序列化,我们先读入第一个字符,以此生成一个根节点,然后再对根节点的左右子节点递归调用去序列化函数即可,参见代码如下:

建议和leetcode 331. Verify Preorder Serialization of a Binary Tree 二叉树的前序序列验证 和 leetcode 654. Maximum Binary Tree 构造最大二叉树 一起学习

建议和leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 中前序构造BST 和 leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal 中后序构造BST 和leetcode 449. Serialize and Deserialize BST 二叉搜索树BST的序列化和反序列化一起学习,疑问做法感觉类似

代码如下:

  1. import java.util.Collections;
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4. /*class TreeNode
  5. {
  6. int val;
  7. TreeNode left;
  8. TreeNode right;
  9. TreeNode(int x) { val = x; }
  10. }
  11. */
  12. /*
  13. * 这个序列化和反序列化就是通过中序来实现
  14. * 要记着这么做
  15. * */
  16. public class Codec
  17. {
  18. private final String delimiter = ",";
  19. private final String nullNode = "#";
  20. // Encodes a tree to a single string.
  21. public String serialize(TreeNode root)
  22. {
  23. StringBuilder builder=new StringBuilder();
  24. serialize(root,builder);
  25. return builder.toString();
  26. }
  27. /*
  28. * 中序遍历得到序列化的值
  29. * */
  30. private void serialize(TreeNode root, StringBuilder builder)
  31. {
  32. if(root==null)
  33. builder.append(nullNode).append(delimiter);
  34. else
  35. {
  36. builder.append(root.val).append(delimiter);
  37. serialize(root.left, builder);
  38. serialize(root.right, builder);
  39. }
  40. }
  41. // Decodes your encoded data to tree.
  42. public TreeNode deserialize(String data)
  43. {
  44. if(data==null || data.length()<=0)
  45. return null;
  46. String[] tmp = data.split(delimiter);
  47. Queue<String> queue=new LinkedList<>();
  48. Collections.addAll(queue, tmp);
  49. TreeNode root=deserialize(queue);
  50. return root;
  51. }
  52. private TreeNode deserialize(Queue<String> queue)
  53. {
  54. if(queue==null || queue.size()<=0)
  55. return null;
  56. String one=queue.poll();
  57. if(one.equals(nullNode))
  58. return null;
  59. else
  60. {
  61. TreeNode root=new TreeNode(Integer.parseInt(one));
  62. root.left=deserialize(queue);
  63. root.right=deserialize(queue);
  64. return root;
  65. }
  66. }
  67. }
  68. // Your Codec object will be instantiated and called as such:
  69. // Codec codec = new Codec();
  70. // codec.deserialize(codec.serialize(root));

下面是C++的做法,这道题十分的棒们很值得学习

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. /*
  20. struct TreeNode
  21. {
  22. int val;
  23. TreeNode *left;
  24. TreeNode *right;
  25. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  26. };
  27. */
  28. class Codec
  29. {
  30. public:
  31. // Encodes a tree to a single string.
  32. string serialize(TreeNode* root)
  33. {
  34. stringstream ss;
  35. dfs1(ss,root);
  36. return ss.str();
  37. }
  38. void dfs1(stringstream &ss,TreeNode* root)
  39. {
  40. if (root == NULL)
  41. ss << "#" << " ";
  42. else
  43. {
  44. ss << root->val << " ";
  45. dfs1(ss,root->left);
  46. dfs1(ss,root->right);
  47. }
  48. }
  49. // Decodes your encoded data to tree.
  50. TreeNode* deserialize(string data)
  51. {
  52. stringstream ss(data);
  53. return dfs2(ss);
  54. }
  55. TreeNode* dfs2(stringstream &ss)
  56. {
  57. string one = "";
  58. ss >> one;
  59. if (one == "#")
  60. return NULL;
  61. else
  62. {
  63. TreeNode* root = new TreeNode(stoi(one));
  64. root->left = dfs2(ss);
  65. root->right = dfs2(ss);
  66. return root;
  67. }
  68. }
  69. };
  70. // Your Codec object will be instantiated and called as such:
  71. // Codec codec;
  72. // codec.deserialize(codec.serialize(root));

发表评论

表情:
评论列表 (有 0 条评论,225人围观)

还没有评论,来说两句吧...

相关阅读