[LeetCode] Serialize and Deserialize Binary Tree
2015-10-30 15:51
411 查看
I adopt a way similar to that of the OJ to serialize the binary tree. For the following tree, my serialization result is "1,2,3,null,null,4,5," (note the last comma).
The serialization and deserialization both use the BFS traversal. The code is as follows.
1 / \ 2 3 / \ 4 5
The serialization and deserialization both use the BFS traversal. The code is as follows.
/** * 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: // Encodes a tree to a single string. string serialize(TreeNode* root) { vector<string> nodes; queue<TreeNode*> level; level.push(root); while (!level.empty()) { int n = level.size(); for (int i = 0; i < n; i++) { TreeNode* node = level.front(); level.pop(); nodes.push_back(node ? to_string(node->val) + "," : "null,"); if (node) { level.push(node->left); level.push(node->right); } } } while (!nodes.empty() && nodes.back() == "null,") nodes.pop_back(); string tree; for (string node : nodes) tree += node; return tree; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data.empty()) return NULL; stringstream ss(data); string vs; getline(ss, vs, ','); TreeNode* root = new TreeNode(stoi(vs)); queue<TreeNode*> level; level.push(root); while (!level.empty()) { int n = level.size(); for (int i = 0; i < n; i++) { TreeNode* node = level.front(); level.pop(); if (getline(ss, vs, ',') && vs != "null") { node->left = new TreeNode(stoi(vs)); level.push(node -> left); } if (getline(ss, vs, ',') && vs != "null") { node->right = new TreeNode(stoi(vs)); level.push(node -> right); } } } return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
相关文章推荐
- springmvc 1
- 数据库查询优化器的艺术:原理解析与SQL性能优化
- SpringMVC中处理404静态页面操作
- noip2013 积木大赛 (贪心)
- PHP trim() 函数
- 七牛上传文件 图片
- java 乱码原因分析
- Codeforces Round #327 (Div. 2) E. Three States bfs
- openstack中虚拟机和其网络的联系方法 instance and network
- 使用JavaScript正则表达式如何去掉双引号
- 在使用O_APPEND 标志并以写打开一个已存在的文件,然后用lseek函数将偏移置于开头,在写入数据,写入的数据会显示在那个位置呢???
- I18N
- POJ2247 Humble Numbers
- 52.VC(Custom)-vc助手–支持预生成宏、注释
- 用来显示学生的信息
- erl_tree RBT 红黑树
- angularjs 绑定enter事件的两种方法
- 淘宝基础版全屏table布局代码
- spring mvc和struts2比较
- Android Studio导入jar后无法识别、但项目能正常运行的问题