/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/** Encodes a tree to a single string. */
struct stack {
char *str;
int top;
};
void initStack(struct stack *S)
{
S->str = malloc(sizeof(char) * 100000);
S->top = -1;
return;
}
void Push(struct stack *S, char element)
{
S->str[++S->top] = element;
return;
}
void Pop(struct stack *S)
{
S->top--;
return;
}
void int2string(int val, struct stack *S)
{
char temp[20];
int m = val;
int i = 0;
int len;
if(m==0)
Push(S,'0');
else
{
while (m)
{
temp[i++] = m%10 + 48;
m = m / 10;
}
temp[i] = '\0';
len = i;
for (i = 0; i < (len / 2); i++)
{
temp[i] = temp[i] + temp[len - 1 - i];
temp[len - i - 1] = temp[i] - temp[len - 1 - i];
temp[i] = temp[i] - temp[len - i - 1];
}
for (i = 0; i < len; i++)
Push(S, temp[i]);
}
return;
}
void preOrder(struct TreeNode *root, struct stack *S)
{
if (!root)
return;
int2string(root->val, S);
Push(S, '#');
preOrder(root->left, S);
preOrder(root->right, S);
return;
}
int string2int(char *data,int *nums)
{
int i,j,temp,len;
int count=0;
for(i=0;data[i]!='\0';i++)
{
temp=0;
j=i+1;
while(data[j]!='#')
j++;
len=j-i;
while(len)
{
temp=(data[i]-48)+temp*10;
len--;
i++;
}
nums[count++]=temp;
}
return count;
}
void BST_insert(struct TreeNode *root, struct TreeNode *p)
{
if (root->val > p->val)
{
if (root->left)
BST_insert(root->left, p);
else
root->left = p;
}
else
{
if (root->right)
BST_insert(root->right, p);
else
root->right = p;
}
return;
}
char* serialize(struct TreeNode* root) {
if(!root)
return NULL;
struct stack s;
initStack(&s);
preOrder(root, &s);
char *p = malloc(sizeof(char)*(s.top + 2));
memcpy(p, s.str, s.top + 1);
p[s.top + 1] = '\0';
return p;
}
/** Decodes your encoded data to tree. */
struct TreeNode* deserialize(char* data) {
if(!data)
return NULL;
int *nums=malloc(sizeof(int)*10000);
int len=string2int(data,nums);
struct TreeNode *root=malloc(sizeof(struct TreeNode));
root->val=nums[0];
root->left=NULL;
root->right=NULL;
for (int i = 1; i < len; i++)
{
struct TreeNode *p = malloc(sizeof(struct TreeNode));
p->val = nums[i];
p->left = NULL;
p->right = NULL;
BST_insert(root, p);
}
return root;
}
// Your functions will be called as such:
// char* data = serialize(root);
// deserialize(data);