Careercup - Facebook面试题 - 5729456584916992
2014-05-02 01:03
375 查看
2014-05-02 00:59
题目链接
原题:
题目:给定一棵二叉树,请设计序列化和反序列化的方法。
解法:我的方法是使用前序遍历来进行序列化,其中大括号"{}"包含了数据序列,用“#”表示空指针。反序列化的思路则相反。
代码:
题目链接
原题:
Given a normal binary tree, write a function to serialize the tree into a string representation (returning the string), and also a function to deserialize a serialized string into the original binary tree.
题目:给定一棵二叉树,请设计序列化和反序列化的方法。
解法:我的方法是使用前序遍历来进行序列化,其中大括号"{}"包含了数据序列,用“#”表示空指针。反序列化的思路则相反。
代码:
// http://www.careercup.com/question?id=5729456584916992 #include <cstdio> #include <string> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {}; }; class BinaryTreeSerializer { public: string serialize(TreeNode *root) { string res = "{"; // preorder traversal serializeTraversal(root, res); res[res.length() - 1] = '}'; return res; }; TreeNode *deserialize(string s) { vector<string> data; int i, j, len; len = (int)s.length(); i = 1; while (true) { j = i + 1; while (s[j] != ',' && s[j] != '}') { ++j; } data.push_back(s.substr(i, j - i)); i = j + 1; if (i >= len) { break; } } int iter = 0; TreeNode *root = nullptr; // preorder traversal deserializeTraversal(data, root, iter); return root; }; private: static char ss[10]; void serializeTraversal(TreeNode *root, string &res) { if (root == nullptr) { res += "#,"; } else { sprintf(ss, "%d", root->val); res += string(ss); res.push_back(','); serializeTraversal(root->left, res); serializeTraversal(root->right, res); } }; void deserializeTraversal(vector<string> &data, TreeNode *&root, int &iter) { ++iter; if (data[iter - 1] == "#") { root = nullptr; } else { int val; sscanf(data[iter - 1].c_str(), "%d", &val); root = new TreeNode(val); deserializeTraversal(data, root->left, iter); deserializeTraversal(data, root->right, iter); } }; };
相关文章推荐
- Careercup - Facebook面试题 - 4909367207919616
- Careercup - Facebook面试题 - 6685828805820416
- Careercup - Facebook面试题 - 23594662
- Careercup - Facebook面试题 - 5412018236424192
- Careercup - Facebook面试题 - 23869663
- Careercup - Facebook面试题 - 6139456847347712
- Careercup - Facebook面试题 - 5761467236220928
- Careercup - Facebook面试题 - 4922014007558144
- Careercup - Facebook面试题 - 5188884744896512
- Careercup - Facebook面试题 - 5890898499993600
- Careercup - Facebook面试题 - 5435439490007040
- Careercup - Facebook面试题 - 4907555595747328
- Careercup - Facebook面试题 - 5177378863054848
- Careercup - Facebook面试题 - 5110993575215104
- Careercup - Facebook面试题 - 6321181669982208
- Careercup - Facebook面试题 - 4892713614835712
- Careercup - Facebook面试题 - 5765850736885760
- Careercup - Facebook面试题 - 5998719358992384
- Careercup - Facebook面试题 - 4713484755402752
- Careercup - Facebook面试题 - 5344154741637120