主页 > 开源代码  > 

Leetcode297.二叉树的序列化与反序列化

Leetcode297.二叉树的序列化与反序列化

文章目录 题目代码(9.30 首刷自解)

题目

297. 二叉树的序列化与反序列化

代码(9.30 首刷自解) class Codec { public: string SEP = ","; string NULL_STR = "#"; // Encodes a tree to a single string. string serialize(TreeNode* root) { if(!root) return NULL_STR + SEP; string res = to_string(root->val) + SEP; res += serialize(root->left); res += serialize(root->right); return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { deque<string> nodes; string tmp; for(char& c : data) { if(string(1,c) != SEP) { tmp += c; } else { nodes.emplace_back(tmp); tmp.clear(); } } return help(nodes); } TreeNode* help(deque<string>& nodes) { auto front = nodes.front(); nodes.pop_front(); if(front == NULL_STR) return nullptr; auto root = new TreeNode(stoi(front)); root->left = help(nodes); root->right = help(nodes); return root; } };
标签:

Leetcode297.二叉树的序列化与反序列化由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Leetcode297.二叉树的序列化与反序列化