leetcode 449. Serialize and Deserialize BST 二叉搜索树BST的序列化和反序列化

待我称王封你为后i 2022-06-04 09:10 212阅读 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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless

题意很简单,就是考察二叉搜索树BST的序列化和反序列化

建议和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 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化 + 深度优先遍历DFS一起学习,疑问做法感觉类似

代码如下:

  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. serialize(root, ss);
  36. return ss.str();
  37. }
  38. void serialize(TreeNode* root, stringstream& ss)
  39. {
  40. if (root==NULL)
  41. ss << "# ";
  42. else
  43. {
  44. ss << root->val << " ";
  45. serialize(root->left, ss);
  46. serialize(root->right, ss);
  47. }
  48. }
  49. // Decodes your encoded data to tree.
  50. TreeNode* deserialize(string data)
  51. {
  52. stringstream ss(data);
  53. return deserialize(ss);
  54. }
  55. TreeNode* deserialize(stringstream& ss)
  56. {
  57. string val = "";
  58. ss >> val;
  59. if (val == "#")
  60. return NULL;
  61. else
  62. {
  63. TreeNode* node = new TreeNode(stoi(val));
  64. node->left = deserialize(ss);
  65. node->right = deserialize(ss);
  66. return node;
  67. }
  68. }
  69. };

发表评论

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

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

相关阅读