【LeetCode】297. Serialize and Deserialize Binary Tree
2024-09-05 21:27:10
二叉树的序列化与反序列化。
如果使用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));
最新文章
- 【Junit 报错】Test class should have exactly one public zero-argument constructor和Test class can only have one constructor
- 130712周赛(CF)
- VelocityTracker简单用法
- 动态修改 C 语言函数的实现
- hdu 1205
- 破解.net程序 编译和反编译方法
- 直接插入排序---java实现
- HoloLens开发手记 - 构建2D应用 Building 2D apps
- RMI,RPC,SOAP对比分析
- 编译httpd细节
- css基础语法三
- RISC_CPU
- Jenkins--发送邮件配置
- BZOJ.4299.Codechef FRBSUM(主席树)
- 框架: Struts2 讲解 1
- Mongodb查询提示com.MongoDB.MongoException: too much data for sort() with no index
- 两个JS的不好设计
- java 对mongodb的操作
- 使用Phantom omni力反馈设备控制机器人
- 深度学习领域的Papers
热门文章
- Deepin-安装git
- axis2开发webservice之编写Axis2模块(Module)
- 【iOS系列】-textView的非常规使用
- Axure安装fontawesome字体
- hibernate could not resolve property
- Hadoop 解除 “Name node is in safe mode”
- 卸载ubuntu自带openJDK,更改成自己的JDK版本
- python iterable 和list、dictionary的区别和联系
- 电商系统的演变可以看出架构演变 Dubbo入门 远程过程调用 需要解决的问题
- Linux如何查看进程等常用命令