剑指offer:面试题37. 序列化二叉树
生活随笔
收集整理的這篇文章主要介紹了
剑指offer:面试题37. 序列化二叉树
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:序列化二叉樹
請(qǐng)實(shí)現(xiàn)兩個(gè)函數(shù),分別用來序列化和反序列化二叉樹。
示例:?
你可以將以下二叉樹:
? ? 1
? ?/ \
? 2 ? 3
? ? ?/ \
? ? 4 ? 5
序列化為 "[1,2,3,null,null,4,5]"
解題:
/*** 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 {
private:// 1,2,#,#,3,-4,#,#,5,#,#,void encode(TreeNode* root, string& res) {if (!root) {res += "#,";return;}res += to_string(root->val) + ",";encode(root->left, res);encode(root->right, res);}TreeNode* decode(int& p, const string& data) {if (data[p] == '#') {p += 2;return NULL;}bool isN = false;if (data[p] == '-') { // 負(fù)數(shù)的情況isN = true;p++;}int num = 0; // 還原成整數(shù)while (data[p] != ',') {num = num * 10 + data[p] - '0';p++;}p++;if (isN) num = -num;auto root = new TreeNode(num);root->left = decode(p, data);root->right = decode(p, data);return root;}public:// Encodes a tree to a single string.string serialize(TreeNode* root) {string res = "";encode(root, res);return res;}// Decodes your encoded data to tree.TreeNode* deserialize(string data) {int p = 0;return decode(p, data);}
};
?
總結(jié)
以上是生活随笔為你收集整理的剑指offer:面试题37. 序列化二叉树的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer:面试题36. 二叉搜索树
- 下一篇: 剑指offer:面试题38. 字符串的排