#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
typedef struct bintree{
char* word;
struct bintree* left;
struct bintree* right;
}Bin;
void restore(Bin** bin, char* tree, int start){
int i, a, num_left, num_right;
char s[100];
num_left = 0;
num_right = 0;
for(i=start; num_left - num_right != 1 || i== start + 1; i++){
if(tree[i] == '(')
num_left+= 1;
if(tree[i] == ')')
num_right+=1;
if(num_left - num_right == 0)
return;
}
a = 0;
for(i; tree[i] != '('; i++){
s[a] = tree[i];
a++;
}
s[a] = '\0';
if(*bin == NULL){
*bin = malloc(sizeof(Bin));
memset(*bin, 0, sizeof(Bin));
(*bin)->word = malloc(strlen(s));
strcpy((*bin)->word, s);
}
restore(&((*bin)->left), tree, start+1);
restore(&((*bin)->right), tree, i);
}
void show(Bin* bin){
if(bin == NULL)
return;
else{
show(bin->left);
printf("%s\n", bin->word);
show(bin->right);
}
}
int main(int argc, char** argv){
Bin* bin;
bin = 0;
restore(&bin, argv[1], 0);
printf("\n");
show(bin);
return 0;
}
(左側の要素 自分の要素 右側の要素)
で、左(右)の要素がNULLだった場合は、()であらわす。
例えば、rootノードがlionで、左側がkoala 右側がdog
だった場合は、
((()koala())lion(()dog()))
っていう風に表現される。
で、この木のdogの右に、catを追加した場合は、
次のようになる。
((()koala())lion(()dog(()cat())))
ってなる。
そこで、この表現から、木を再構築するアルゴリズムを書いたわけです。
引数に、この表現が渡されて、それを二分木に再構築するわけです。
エラー処理はしてないけど、そこ以外のところで改善点がほしいです。たとえば、もっと高速、効率的なのがあるとか。