char* serializeHelper(struct TreeNode* root, int* len) { *len = 2; if(!root) return "X,"; //convert null node to X ended with comma; char *t = (char*)malloc(sizeof(char)*LEN); int size = 0; int val = root->val; while(val) //invert integer to string; { t[size++] = val%10 + '0'; val /= 10; } for(int i = 0; i < size/2; i++) //revert the string; { char c = t[size-i-1]; t[size-i-1]=t[i]; t[i]=c; } t[size++] = ','; //ended with comma as splitter; t[size] = '\0'; int leftLen=0, rightLen=0; char *left = serializeHelper(root->left, &leftLen); char *right = serializeHelper(root->right, &rightLen); *len = size+leftLen+rightLen+2; t = (char*)realloc(t, sizeof(char)*(*len)); strcat(t, left); strcat(t, right); return t; }
void serializeHelper(TreeNode* root, ostringstream& out) { if (root) { out << root->val << ' '; serializeHelper(root->left, out); serializeHelper(root->right, out); } else { out << '#' << ' '; } }
void serializeHelper(TreeNode *root, string &prev) { if (!root) { prev += "# "; } else { stringstream buffer; buffer << root->val << " "; prev += buffer.str(); serializeHelper(root->left, prev); serializeHelper(root->right, prev); } }
void serializeHelper(TreeNode *root, string &output) { if (!root) { output += "# "; return; } else { stringstream buffer; buffer << root->val << " "; output += buffer.str(); serializeHelper(root->left, output); serializeHelper(root->right, output); } }
void rice::p2p::scribe::messaging::AnycastMessage::serialize(::rice::p2p::commonapi::rawserialization::OutputBuffer* buf) /* throws(IOException) */ { npc(buf)->writeByte(static_cast< int8_t >(int32_t(1))); serializeHelper(buf); }
/** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { string output; serializeHelper(root, output); return output; }
/** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { // write your code here string output; serializeHelper(root, output); return output; }
//AC - 16ms; char* serialize(struct TreeNode* root) { int len = 0; return serializeHelper(root, &len); }