字符序列转N叉树

 

//输入如a(b(c,d),e,f(g,h,i))的序列,生成3叉树,并递归打印
#include <stdio.h>
#include
<stdlib.h>
#include
<string.h>
#include
<assert.h>

#define N 3
#define BUF_SIZE 1024

char buf[BUF_SIZE], *str = buf;

typedef
struct Node
{
char val;
struct Node *subTree[N];
}Node,
*PNode, *Tree;

Tree MakeTree()
{
int i;
PNode pNode
= NULL;

pNode
= (PNode)malloc(sizeof(Node));
assert(pNode
!= NULL);
memset(pNode,
0, sizeof(Node));
pNode
->val = *str++;
if('(' == *str)
{
str
++;
i
= 0;
do {
pNode
->subTree[i] = MakeTree();
if(',' == *str)
str
++;
else if(')' == *str++)
break;
i
++;
}
while (i < N);
}
return pNode;
}

void WalkTree(Tree tree)
{
int i;

if(NULL != tree)
{
putchar(tree
->val);
if(tree->subTree[0] == NULL)
return;
putchar(
'(');
for(i = 0; i < N; i++)
{
WalkTree(tree
->subTree[i]);
if(i + 1 < N && tree->subTree[i + 1] != NULL)
putchar(
',');
}
putchar(
')');
}
}

int main()
{
Tree tree
= NULL;
printf(
"input str: ");
while(scanf("%s", buf) != EOF)
{
str
= buf;
tree
= MakeTree();
WalkTree(tree);
printf(
"\ninput str: ");
}
return 0;
}

 

 

 

posted @ 2010-10-11 17:23  penink  阅读(210)  评论(0)    收藏  举报