当前位置: 代码迷 >> 综合 >> 剑指offer:面试题37. 序列化二叉树
  详细解决方案

剑指offer:面试题37. 序列化二叉树

热度:14   发布时间:2024-01-26 21:49:47.0

题目:序列化二叉树

请实现两个函数,分别用来序列化和反序列化二叉树。

示例: 

你可以将以下二叉树:

    1
/ \
2   3
/ \
4   5

序列化为 "[1,2,3,null,null,4,5]"


解题:

/*** 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 {
private:// 1,2,#,#,3,-4,#,#,5,#,#,void encode(TreeNode* root, string& res) {if (!root) {res += "#,";return;}res += to_string(root->val) + ",";encode(root->left, res);encode(root->right, res);}TreeNode* decode(int& p, const string& data) {if (data[p] == '#') {p += 2;return NULL;}bool isN = false;if (data[p] == '-') {  // 负数的情况isN = true;p++;}int num = 0;  // 还原成整数while (data[p] != ',') {num = num * 10 + data[p] - '0';p++;}p++;if (isN) num = -num;auto root = new TreeNode(num);root->left = decode(p, data);root->right = decode(p, data);return root;}public:// Encodes a tree to a single string.string serialize(TreeNode* root) {string res = "";encode(root, res);return res;}// Decodes your encoded data to tree.TreeNode* deserialize(string data) {int p = 0;return decode(p, data);}
};

 

  相关解决方案