1: /** 2: * Definition for a binary tree node. 3: * struct TreeNode { 4: * int val; 5: * TreeNode *left; 6: * TreeNode *right; 7: * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8: * }; 9: */ 10: class Codec { 11: public: 12: // Encodes a tree to a single string. 13: string serialize(TreeNode* root) { 14: if (root == NULL) return "#"; 15: string s = to_string(root->val) + "," + serialize(root->left) + "," + serialize(root->right); 16: return s; 17: } 18: // Decodes your encoded data to tree. 19: TreeNode* deserialize(string data) { 20: return helper(data); 21: } 22: TreeNode* helper(string &data) { 23: if (data[0] == '#') { 24:
if (data.size() > 1)
data = data.substr(2); 25: return NULL; 26: } 27: TreeNode *root = new TreeNode(integer(data)); 28: root->left = helper(data); 29: root->right = helper(data); 30: return root; 31: } 32: int integer(string &data) { 33: int i = data.find(','); 34: int val = stoi(data.substr(0, i)); 35: data = data.substr(i+1); 36: return val; 37: } 38: }; 39: // Your Codec object will be instantiated and called as such: 40: // Codec codec; 41: // codec.deserialize(codec.serialize(root));
Friday, July 8, 2016
297. Serialize and Deserialize Binary Tree
The serialization and deserialization can be done by preorder tree traversal. When I revisit the problem, I made a mistake in line 24. Without this line, there'll be "Runtime Error" when input is "null".
Labels:
amazon,
google,
leetcode,
preorder traversal,
serialization,
string,
tree
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment