二叉树的序列化与反序列化。

如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便。

这里学会了使用 sstream 中的 输入流'istringstream' 和 输出流'ostringstream'.

istringstream in;

in >> str;

这里没执行一次就会倒出一个string (因为in流中使用了' '空格 作为分割符, 所以可以分成很多个string)

建树的时候使用先序建立二叉树。

关键代码如下:

TreeNode* build(istringstream in){
if(#) return null;
else{
new a node
newnode -> left = build(in)
newnode -> right = build(in)
}
}
/**
* 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) {
ostringstream out;
backtrack(root, out);
return out.str();
} // Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data);
return build(in);
} private:
void backtrack(TreeNode *rt, ostringstream &out){
if(rt){
out << rt -> val << " ";
backtrack(rt -> left, out);
backtrack(rt -> right, out);
}else{
out << "#"<<" ";
}
} // 形如: 1 # 2 其中树节点必为满树空节点用#表示。中间用空格分割。
TreeNode* build(istringstream &in){
string str = "";
in >> str;
if(str == "#" || str == ""){
return NULL;
}else{
TreeNode *rt = new TreeNode(atoi(str.c_str()));
rt -> left = build(in);
rt -> right = build(in);
return rt;
}
}
}; // Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

最新文章

  1. 【Junit 报错】Test class should have exactly one public zero-argument constructor和Test class can only have one constructor
  2. 130712周赛(CF)
  3. VelocityTracker简单用法
  4. 动态修改 C 语言函数的实现
  5. hdu 1205
  6. 破解.net程序 编译和反编译方法
  7. 直接插入排序---java实现
  8. HoloLens开发手记 - 构建2D应用 Building 2D apps
  9. RMI,RPC,SOAP对比分析
  10. 编译httpd细节
  11. css基础语法三
  12. RISC_CPU
  13. Jenkins--发送邮件配置
  14. BZOJ.4299.Codechef FRBSUM(主席树)
  15. 框架: Struts2 讲解 1
  16. Mongodb查询提示com.MongoDB.MongoException: too much data for sort() with no index
  17. 两个JS的不好设计
  18. java 对mongodb的操作
  19. 使用Phantom omni力反馈设备控制机器人
  20. 深度学习领域的Papers

热门文章

  1. Deepin-安装git
  2. axis2开发webservice之编写Axis2模块(Module)
  3. 【iOS系列】-textView的非常规使用
  4. Axure安装fontawesome字体
  5. hibernate could not resolve property
  6. Hadoop 解除 “Name node is in safe mode”
  7. 卸载ubuntu自带openJDK,更改成自己的JDK版本
  8. python iterable 和list、dictionary的区别和联系
  9. 电商系统的演变可以看出架构演变 Dubbo入门 远程过程调用 需要解决的问题
  10. Linux如何查看进程等常用命令