Serialize and Deserialize Binary Tree(C++二叉树的序列化与反序列化)

以你之姓@ 2022-09-07 00:08 244阅读 0赞

(1)先序遍历+队列

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Codec {
  11. public:
  12. // Encodes a tree to a single string.
  13. string serialize(TreeNode* root) {
  14. if(!root) return "nullptr,";
  15. return to_string(root->val)+','+serialize(root->left)+serialize(root->right);
  16. }
  17. TreeNode *helper(queue<string> &q) {
  18. string s=q.front();
  19. q.pop();
  20. if(s=="nullptr") return nullptr;
  21. TreeNode *root=new TreeNode(stoi(s));
  22. root->left=helper(q);
  23. root->right=helper(q);
  24. return root;
  25. }
  26. // Decodes your encoded data to tree.
  27. TreeNode* deserialize(string data) {
  28. queue<string> q;
  29. string s="";
  30. for(int i=0;i<data.length();i++) {
  31. if(data[i]==',') {
  32. q.push(s);
  33. s="";
  34. } else s+=data[i];
  35. }
  36. return helper(q);
  37. }
  38. };
  39. // Your Codec object will be instantiated and called as such:
  40. // Codec ser, deser;
  41. // TreeNode* ans = deser.deserialize(ser.serialize(root));

发表评论

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

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

相关阅读