# Serialize and Deserialize binary tree ```cpp= class Codec { public: // 1(2()())(3(4()())(5()())) // Encodes a tree to a single string. string serialize(TreeNode* root) { if (root == NULL) { return string(""); } string num = to_string(root->val); return num + "(" + serialize(root->left) + ")(" + serialize(root->right) + ")"; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { int nextStart = 0; return parse(data, 0, &nextStart); } TreeNode* parse(string& data, int cur, int* nextStart) { if (cur >= data.size()) { return NULL; } if (data[cur] == ')') { *nextStart = cur + 1; return NULL; } int numEnd = data.find_first_of("(", cur); int num = stoi(data.substr(cur, numEnd - cur)); TreeNode* node = new TreeNode(num); node->left = parse(data, numEnd + 1, nextStart); node->right = parse(data, *nextStart + 1, nextStart); *nextStart += 1; return node; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up