#include <stdio.h>
#include <string.h>

#define MAXNAME 128
struct node
{ // 木構造のノード
    struct node *left, *right; // 左と右の分岐
    char name[MAXNAME]; // ノードの名前（関数，定数，変数）
};

void get_next_token(char *buf)
{ // 次のトークン（記号，数値）を探す
  int    ibuf;
  int    i = 0;
  while ((ibuf = getchar()) != EOF) {
    if (isspace((char) ibuf)) { //タブ，空白のとき終了
      buf[i] = '\0';
      break;
    } else if (((char) ibuf) == ')') {
      ungetc((char) ibuf,stdin); // 一文字読み戻す
      buf[i] = '\0';
      break;
    } else {
      buf[i++] = (char) ibuf;
    }
  }
}


#define TRACE 0 // １にすると読み込むたびに出力する
struct node *read_tree()
{ // 再帰的に木構造を読み込む
  int    i;
  struct node *t;
  char    buf[80];
  
  if (scanf("%1s",buf) == EOF) return (struct node *) EOF;

  if ((t = (struct node *) malloc(sizeof(struct node))) == NULL) {
    printf("Error: memory overflow\n");
    exit(1);
  }
  if (buf[0] == '(') {
    if (TRACE) printf("(");
    scanf("%1s", buf);
    ungetc(buf[0],stdin); // 一文字読み戻す
    get_next_token(buf); // 次のトークンを得る
    if (TRACE) printf("%s ",buf);
    strcpy(t->name,buf); // ノードの名前に入力
    t->left = read_tree(); // 左の木の入力
    t->right = read_tree(); // 右の木の入力
    scanf(")");
    if (TRACE) printf(")\n");
  } else {
    ungetc(buf[0],stdin); // 一文字読み戻す
    get_next_token(buf); // 次のトークンを得る
    if (TRACE) printf("%s ",buf);
    strcpy(t->name,buf); // ノードの名前に入力
    t->left = NULL; // 終端の記号なのでNULLを入れる
    t->right = NULL; // 終端の記号なのでNULLを入れる
  }
  return(t);
}

void print_tree(struct node *nd)
{ // 再帰的に木構造を書き出す
    if ((nd->left == NULL) && (nd->right == NULL)) {
        printf(" %s",nd->name); // ノードの名前を書く
        return;
    }
    printf("(%s ",nd->name);
    if (nd->left != NULL) print_tree(nd->left); // まず左の木を書く
    if (nd->right != NULL) print_tree(nd->right); // まず右の木を書く
    printf(")");
}

void free_tree(struct node *nd)
{ // 木構造のメモリを解放する
    if (nd->left != NULL) free_tree(nd->left);
    if (nd->right != NULL) free_tree(nd->right);
    free(nd);
}

#define MAXCT 10 // 木を扱う回数
main()
{
    struct node *root,*current;
    int ct=0;
    while (ct++<MAXCT) {
    root = read_tree();
    printf("--->\n");
    print_tree(root);
    printf("\n");
    free_tree(root); // 不要になった木構造のメモリを解放する
    }
}
