建立二叉树的二叉链表存储结构(严6.70)

Description

如果用大写字母标识二叉树结点,则一颗二叉树可以用符合下面语法图的字符序列表示。试编写递归程序,由这种形式的字符序列,建立相应的二叉树的二叉链表存储结构(附图见《严蔚敏:数据结构题集(C语言版)》第45页6.70)。

Input

输入如图所示的字符序列。

Output

建立相应二叉树的二成叉链表存储结构,并先序遍历输出。

  • Sample Input 
    A(B(#,D),C(E(#,F),#))
  • Sample Output
    AB#DCE#F#
正常做法:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef struct BinTreeNode
{
	char  data;
	struct BinTreeNode	*lchild;
	struct BinTreeNode	*rchild;
};

struct BinTreeNode *CreateTree()
{
    char s,s1;
    struct BinTreeNode *q;
    q=(struct BinTreeNode*)malloc(sizeof(struct BinTreeNode));
    s=getchar();
    s1=s;
    s=getchar();
    q->lchild=NULL;
    q->rchild=NULL;
    if(s1==',')
    {
        q->data=s;
        s1=getchar();
        if (s1=='(')
        {
            q->lchild=CreateTree();
            q->rchild=CreateTree();
        }
    }
    else
    {
        q->data=s1;
        if (s=='(')
        {
            q->lchild=CreateTree();
            q->rchild=CreateTree();
        }
    }
    return q;
}

void PrintBinTree (struct BinTreeNode *p)
{
    printf("%c",p->data);
    if(p->lchild)
    {
        PrintBinTree(p->lchild);
    }
    if(p->rchild)
    {
        PrintBinTree(p->rchild);
    }
}

int main()
{
    BinTreeNode *head;
    head=CreateTree();
    PrintBinTree(head);
    return 0;
}

这道题如果只是想AC,有一个简单做法(亲测可以AC):
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

int main()
{
    char str[10005];
    char ans[10005];
    gets(str);
    int j=0;
    for(int i=0;str[i]!='\0';i++)
    {
        if(str[i]!='('&&str[i]!=')'&&str[i]!=',')
        {
            ans[j]=str[i];
            j++;
        }
    }
    ans[j]='\0';
    printf("%s\n",ans);
    return 0;
}
补充知识:含有n个结点的不相似的二叉树有An= [1/(n+1)]*C(n 2n)棵。

补充……我觉得当时建树没建好,具体参考https://blog.csdn.net/zhao2018/article/details/80754319
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值