设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
注意事项
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output ofserialize
as the input of deserialize
, it won‘t check the result of serialize.
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7}
,表示如下的树结构:
3
/ 9 20
/ 15 7
我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。
你可以采用其他的方法进行序列化和反序列化。
思路:在这里使用先根遍历来实现;
本题目难点在于,里面穿插关于字符串和整数间的互相转换。
在序列化时,空节点的表示,不同节点值之间的分割。
在反序列化时,字符串每个字符遍历时的控制条件和操作,以及将字符串转换为整数;
参考:http://blog.csdn.net/waltonhuang/article/details/51979479
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ /* 思路:感觉上用BFS更容易解决,在这里使用先根遍历来实现; 参考:http://blog.csdn.net/waltonhuang/article/details/51979479 本题目难点在于,里面穿插关于字符串和整数间的互相转换。 在序列化时,空节点的表示,不同节点值之间的分割。 在反序列化时,字符串每个字符遍历时的控制条件和操作,以及将字符串转换为整数; */ string serialize(TreeNode *root) { // write your code here string s = ""; writeTree(s, root); return s; } void writeTree(string &s, TreeNode* root){ if (root == NULL){ s += "# "; return; } s += (to_string(root->val) + ‘ ‘); writeTree(s, root->left); writeTree(s, root->right); } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it‘s given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ TreeNode *deserialize(string data) { // write your code here int pos = 0; return readTree(data, pos); } TreeNode* readTree(string data, int& pos){ if (data[pos] == ‘#‘){ pos += 2; return NULL; } int nownum = 0; while (data[pos] != ‘ ‘){ //这里‘ ‘是为了分离不同的数字; nownum = nownum * 10 + (data[pos] - ‘0‘); pos++; } pos++; TreeNode* nowNode = new TreeNode(nownum); nowNode->left = readTree(data, pos); nowNode->right = readTree(data, pos); return nowNode; } };
时间: 2024-10-08 14:57:04