当前位置:网站首页>297. 二叉树的序列化与反序列化
297. 二叉树的序列化与反序列化
2022-07-31 00:48:00 【anieoo】
原题链接:297. 二叉树的序列化与反序列化
solution
/**
* 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) {
if(root == NULL) {
return "_#";
}
string res = "_" + to_string(root->val);
res += serialize(root->left);
res += serialize(root->right);
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data == "_#") return NULL;
queue<string> q;
int n = data.size();
for(int i = 0;i < n;i++) {
int j = i;
string item;
while(j < n && data[j] != '_') item += data[j++];
i = j;
if(item != "") q.push(item);
}
return helper(q);
}
TreeNode* helper(queue<string>& q)
{
string val = q.front();
q.pop();
if (val == "#")
return NULL;
TreeNode* head = new TreeNode(stoi(val));
head->left = helper(q);
head->right = helper(q);
return head;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
边栏推荐
猜你喜欢
Error occurred while trying to proxy request The project suddenly can't get up
ShardingSphere's unsharded table configuration combat (6)
Summary of MySQL database interview questions (2022 latest version)
BOM系列之Navigator对象
Homework: iptables prevent nmap scan and binlog
Typescript18 - object type
SWM32 Series Tutorial 6 - Systick and PWM
The difference between h264 and h265 decoding
【Multithreading】
typescript16-void
随机推荐
MySQL数据库(基础)
Go study notes (84) - Go project directory structure
ELK deployment script---pro test available
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
Can deep learning solve the parameters of a specific function?
分布式系统的一致性与共识(1)-综述
Redis learning
【Demo】ABAP Base64加解密测试
MySQL triggers
Homework: iptables prevent nmap scan and binlog
SereTOD2022 Track2代码剖析-面向半监督和强化学习的任务型对话系统挑战赛
Error ER_NOT_SUPPORTED_AUTH_MODE Client does not support authentication protocol requested by serv
Go 学习笔记(84)— Go 项目目录结构
Kotlin协程:协程上下文与上下文元素
Meeting OA project pending meeting, all meeting functions
TypeScript在使用中出现的问题记录
Strict Mode for Databases
Unity2D horizontal version game tutorial 4 - item collection and physical materials
typescript15-(同时指定参数和返回值类型)
24. 请你谈谈单例模式的优缺点,注意事项,使用场景