lintcode:Binary Tree Serialization
2016-03-28 23:15
357 查看
Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization’ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization’.
There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.
参考:
/article/4999943.html
可以看到stringstream格式化字符串的强大功能。
There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.
/** * 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. */ void serializeHelper(TreeNode *node,string& res){ if(node){ res+=to_string(node->val)+" "; }else{ res+="# "; return; } serializeHelper(node->left,res); /* if(node->left){ serializeHelper(node->left,res); }else{ res+="# "; }*/ serializeHelper(node->right,res); /* if(node->right){ serializeHelper(node->right,res); }else{ res+="# "; }*/ } string serialize(TreeNode *root) { // write your code here string res=""; serializeHelper(root,res); return res; } /** * 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* deserializeHelper(istringstream& ss){ string str; ss>>str; if(str[0]=='#'){ return NULL; } int value=atoi(str.c_str()); TreeNode *node=new TreeNode(value); node->left=deserializeHelper(ss); node->right=deserializeHelper(ss); return node; } TreeNode *deserialize(string data) { // write your code here istringstream ss(data); TreeNode *root=deserializeHelper(ss); return root; } };
参考:
/article/4999943.html
可以看到stringstream格式化字符串的强大功能。
相关文章推荐
- 文本相似度计算(一)
- 给定矩阵行数和矩阵列数,顺时针打印矩阵(从0开始)
- gentoo linux安装过程中出现的错误及解决方案
- Problem C: 结构体---点坐标结构体
- android 动画 Animation
- Redis集群之twemproxy
- 书到用时方嫌少,多读些书
- 搭建自己的PHP框架心得(一)
- Kernel编译安装
- 在Java中如何高效判断数组中是否包含某个元素
- shell脚本--部署应用到tomcat并启动tomcat
- ios学习 多线程NSThread 基本属性
- SpringMVC与Struts2区别与比较总结
- poj 2136 Vertical Histogram
- android中媒体扫描服务mediaScannerService
- tomcat 的 SSL 配置
- 存储过程的优缺点以及使用过程
- 高精度 java的一些题
- iOS边练边学--应用数据存储的常用方式(plist,Preference,NSKeyedArchiver)其中的三种
- 第五周上机实践项目——项目4-长方柱类