Last active
May 13, 2016 15:45
-
-
Save annidy/c38620588037d82c425aa82d1f787657 to your computer and use it in GitHub Desktop.
leetcode binary tree loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create by annidy | |
// 2016-05-13 | |
#include <stdio.h> | |
#include <utlist.h> | |
#include <string.h> | |
#include <stdlib.h> | |
struct TreeNode { | |
int val; | |
struct TreeNode *left; | |
struct TreeNode *right; | |
}; | |
typedef struct el { | |
struct TreeNode *n; | |
int used; // every n must used 2 times! | |
struct el *next; | |
} el; | |
int count(char *str) | |
{ | |
int n = 0; | |
while (*str) { | |
if (*str++ == ',') | |
n++; | |
} | |
return n+1; | |
} | |
/// user free return | |
struct TreeNode *loader(char *str) { | |
el *head = NULL; | |
el *subhead = NULL; | |
el *tmp; | |
el *elt; | |
size_t len = strlen(str); | |
char *tstr = malloc(len); | |
memcpy(tstr, str+1, len-2); | |
tstr[len-2] = 0; | |
int i = 0; | |
char *val = strtok(tstr, ","); | |
if (!val) { | |
return NULL; // [] | |
} | |
struct TreeNode *tns = calloc(count(str), sizeof(struct TreeNode)); | |
for (; val; val = strtok(NULL, ","), i++) { | |
struct TreeNode *tn = NULL; | |
if (strcmp(val, "null") != 0) { | |
tns[i].val = atoi(val); | |
tn = &tns[i]; | |
// enqeue this to sub list | |
el *sub = calloc(1, (sizeof(struct el))); | |
sub->n = tn; | |
LL_APPEND(subhead, sub); | |
} | |
if (i > 0) { | |
if (head->used++ == 0) { | |
head->n->left = tn; | |
} else { | |
head->n->right = tn; | |
// used twice now! pop it | |
tmp = head->next; | |
free(head); | |
head = tmp; | |
} | |
} | |
if (head == NULL) { // if head empty, swap sub to head | |
tmp = subhead; | |
subhead = head; | |
head = tmp; | |
} | |
} | |
LL_FOREACH_SAFE(subhead,elt,tmp) { | |
LL_DELETE(subhead,elt); | |
free(elt); | |
} | |
return tns; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment