69,371
社区成员
发帖
与我相关
我的任务
分享
void dfs(struct TreeNode *root, char *s);
char* serialize(struct TreeNode* root) {
if(root == NULL)
return NULL;
char *re = (char*)malloc(sizeof(char) * 5000);
dfs(root, re);
return re;
}
void dfs(struct TreeNode *root, char *s)
{
if(root == NULL)
{
strcat(s, "#");//如果是NULL,在字符串后添加“#”;
return;
}
int temp = root->val;
int index = strlen(s);
while(temp)
{
s[index++] =(char)(temp % 10 + '0');//直接将数值,添加在字符串后面,最后加一个空格,区别,数值哪里截至。
temp /= 10;
}
s[index++] = ' ';
s[index] = '\0';
dfs(root->left, s);
dfs(root->right, s);
}
/** Decodes your encoded data to tree. */
struct TreeNode* deserialize(char* data) {
if(data[0] == '\0')
return NULL;
if(data[0] == '#')
{
data = data + 1;//如果传递过来的字符串第一个是"#", 则将字符串地址转换为下一个索引的位置。
return NULL;
}
struct TreeNode * root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 0;
int i = 0;
for(i = 0; data[i] >= '0' && data[i] <= '9'; i++)
{
root->val *= 10;
root->val += (int)(data[i] - '0');
}
data = data + i + 1; //当前的数值,取出后,将字符串的地址改为该数值以及其后空格,之后的一个地址。这里不知道这种操作是否可行??????????
root->left = deserialize(data);
root->right = deserialize(data);
return root;
}
// Your functions will be called as such:
// char* data = serialize(root);
// deserialize(data);
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/** Encodes a tree to a single string. */
void dfs(struct TreeNode *root, char *s);
struct TreeNode* de(char* data, int *index, int len);
char* serialize(struct TreeNode* root) {
if(root == NULL)
return NULL;
char *re = (char*)malloc(sizeof(char) * 5000);
re[0] = '\0';
dfs(root, re);
return re;
}
void dfs(struct TreeNode *root, char *s)
{
if(root == NULL)
{
strcat(s, "#");
return;
}
char *str = (char*)malloc(sizeof(char) *12);
sprintf(str, "%d ", root->val);
//itoa(root->val, str, 10); itoa函数与ANSI标准是不兼容的;
strcat(s, str);
//strcat(s, " ");
free(str);
dfs(root->left, s);
dfs(root->right, s);
}
/** Decodes your encoded data to tree. */
struct TreeNode* deserialize(char* data) {
if(data == NULL)
return NULL;
int index = 0;
int len = strlen(data);
return de(data, &index, len);
}
struct TreeNode* de(char* data, int *index, int len)
{
//int len = strlen(data);
if((*index) >= len)
return NULL;
if((*index) < len && data[*index] == '#')
{
(*index)++;
return NULL;
}
int flag = 1;
if(data[*index] == '-')
{
flag = -1;
(*index)++;
}
else if(data[*index] == '+')
{
(*index)++;
}
struct TreeNode * root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 0;
while((*index) <= len && data[*index] >= '0' && data[*index] <= '9')
{
root->val *= 10;
root->val += (int)(data[(*index)] - '0');
(*index)++;
}
root->val *= flag;
(*index)++;
root->left = de(data, index, len);
root->right = de(data, index, len);
return root;
}
// Your functions will be called as such:
// char* data = serialize(root);
// deserialize(data);