LC 297. Serialize and Deserialize Binary Tree
阿新 • • 發佈:2018-11-22
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(stringdata) { 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));
Follow up:
如果node不是數字而是任意字串怎麼辦。
可以借鑑TCP的思想,每個字串前先記錄字串的個數,如 2#ab 之類的即可。