二叉树的序列化与反序列化

it2022-06-30  86

我们使用二叉树的先序遍历来遍历整个树,对于空子树保存为#,恢复时也根据先序的顺序来恢复297. Serialize and Deserialize Binary Tree

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: void serialize(TreeNode* root, ostringstream& out){ if(root == nullptr) { out << "# "; return; } out << root->val << ' '; serialize(root->left, out); serialize(root->right, out); } // Encodes a tree to a single string. string serialize(TreeNode* root) { ostringstream out; serialize(root, out); return out.str(); } TreeNode* deserialize(istringstream &in){ string data; in >> data; if(data == "#") return nullptr; auto root = new TreeNode(stoi(data)); root->left = deserialize(in); root->right = deserialize(in); return root; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { istringstream in(data); return deserialize(in); } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));

转载于:https://www.cnblogs.com/qbits/p/11164911.html


最新回复(0)