LC 297. Serialize and Deserialize Binary Tree
方法一:PreOrder, Recursive
Serialize a tree,最容易的还是前序遍历,用空格分开节点即可。
Deserialize 也很容易,递归即可。
/** * 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 "#"; return to_string(root->val)+' '+serialize(root->left)+' '+serialize(root->right); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { return dfs(data); } TreeNode* dfs(string &data){ if (data[0]=='#'){ if (data.size()>2) data = data.substr(2); return NULL; }else{ int pos=data.find(' '); TreeNode *node=new TreeNode(stoi(data.substr(0,pos))); data = data.substr(pos+1); node->left = dfs(data); node->right = dfs(data); return node; } } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
方法二:LevelOrder
层次遍历,这种序列化的方式和leetcode序列化的方式基本一样。
Deserialize的时候同样也要用到queue,连接节点与节点。
/** * 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) { string res=""; if (root==NULL) return res; queue<TreeNode *> q({root}); while (!q.empty()){ TreeNode *cur=q.front(); q.pop(); if (cur==NULL) res+=" #"; else{ res += (res==""?"":" ") + to_string(cur->val); q.push(cur->left); q.push(cur->right); } } return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { istringstream in(data); string val; if (!(in>>val)) return NULL; TreeNode *root=new TreeNode(stoi(val)); queue<TreeNode *> q({root}); while (!q.empty()){ TreeNode *cur=q.front(); q.pop(); if (!(in>>val)) break; if (val!="#"){ TreeNode *leftnode=new TreeNode(stoi(val)); cur->left = leftnode; q.push(leftnode); } if (!(in>>val)) break; if (val!="#"){ TreeNode *rightnode=new TreeNode(stoi(val)); cur->right = rightnode; q.push(rightnode); } } return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
Follow up:
如果node不是数字而是任意字符串怎么办。
可以借鉴TCP的思想,每个字符串前先记录字符串的个数,如 2#ab 之类的即可。