btree tmp[MAX_SIZE];
btree p = NULL;
btree tree;
int top = -1;
int k, j = 0;
char ch;
tree = NULL;
ch = *(str + j);
while (ch != '\0') {
switch (ch) {
case '('://左子树
top++;
tmp[top] = p;
k = 1;
break;
case ')':
top--;
break;
case ','://右子树
k = 2;
break;
default:
p = (btree) malloc(sizeof(struct _treenode_));
if (p == NULL) {
perror("malloc.\n");
return NULL;
}
p->data = ch;
p->lchild = p->rchild = NULL;
if (tree == NULL) {
tree = p;
} else {
switch (k) {
case 1:
tmp[top]->lchild = p;
break;
case 2:
tmp[top]->rchild = p;
break;
}
}
}
j++;
ch = *(str + j);
}
return tree;
}
注:输入字符串的形式为:
A,(((B),(C,(D,E),F,(G,H))),I,(J,(L,M),K,(O,P,(a,b,(c,d,(e,f,(g,h,(i,j))))))))
或:
A(B(D,E(G,H)),C(,F(I)))