昂?这例子貌似有问题啊,按你的描述这棵树
R(a(b,c),d(e,f,g),h)
转化为二叉表示之后应该是这个样子的,附过程:
R(a)
R(a(b,d))
R(a(b(NULL,c),d(e,h))
R(a(b(NULL,c),d(e(NULL,f),h))
R(a(b(NULL,c),d(e(NULL,f(NULL,g)),h))
按我理解只需要所二叉表示的树还原为用凹入法表示,是这意思不?
是的话那就很简单了,就是一个前序遍历加一些输出判断。
只写ShowTree的话……活动活动筋骨~~
顺带写了个CreateTree,测试用吧~~
void CreateTree(TreeNode* &root, char sTree[])
{
static int iIndex=0;
bool bChNULL=true;
bool bBrNULL=true;
if(sTree[iIndex])
{
root=(TreeNode*)malloc(sizeof(TreeNode));
root->data = sTree[iIndex];
iIndex++;
if(sTree[iIndex]=='(')
{
iIndex++;
CreateTree(root->child, sTree);
bChNULL=false;
}
if(sTree[iIndex]==',')
{
iIndex++;
CreateTree(root->brother, sTree);
bBrNULL=false;
}
if(sTree[iIndex]==')')
iIndex++;
if(bChNULL)
root->child=NULL;
if(bBrNULL)
root->brother=NULL;
}
}
void ShowTree(TreeNode *root)
{
printf("%c",root->data);
if(root->child)
{
printf("(");
ShowTree(root->child);
printf(")");
}
if(root->brother)
{
printf(",");
ShowTree(root->brother);
}
}
void main()
{
char sTree[]={"R(a(b,c),d(e,f,g),h)"};//随便改做测试,结构别写错了就行了……
TreeNode *root=NULL;
CreateTree(root, sTree);
printf("R(");ShowTree(root->child);printf(")");
//这里传参是按你要求里说的以第一个孩子为链表头,其实可以直接传root的
} |