刘汝佳书--p102

本文介绍了一种基于二叉树的数据结构实现节点插入的方法。通过递归方式遍历树结构,实现节点的有效添加,并确保树的唯一性和完整性。文章详细解释了如何处理重复节点的情况及如何遍历整个树来验证其正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//测试样例:
//(3,l) (4,r) ()
//(11,ll) (7,l) (8,lll) (7,l) (7,) ()
//(11,ll) (7,lll) (4,l) (5,) ()
//(11,ll) (7,l) (8,lll) (7,) ()
//(11,ll) (8,lll) (7,) ()
//(11,ll) (7,lll) (8,r) (5,) (4,l) (13,rl) (2,llr) (1,rrr) (4,rr) ()




#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
const int N=20;
char str[20],c[10];
int a[1<<N];
struct NODE
{
    int v,value;
    struct NODE *l,*r;
    NODE()
    {
        r=l=NULL;
        value=0;
    }
};
NODE *root;
int v;
NODE *newnode()
{
    return new NODE;//不能用malloc,只申请内存,不调用构造函数!!
}
int addnode(int v,char c[])
{
    int i=0;
    NODE *p=root;
    while(c[i])
    {
        if(c[i]=='l')
        {
            if(p->l==NULL)
                p->l=newnode();
            p=p->l;


        }
        else if(c[i]=='r')
        {
            if(p->r==NULL)
                p->r=newnode();
            p=p->r;
        }
        i++;
    }
    if(p->value==1)
    {
        return 0;
    }
    p->value=1;
    p->v=v;
    return 1;
}


int  input()
{
    root=newnode();
    int flag=0;
    while(1)
    {
        if(scanf("%s",str)!=1)
            return 0;
        if(!strcmp(str,"()"))
            break;
        sscanf(str,"(%d,%s",&v,c);//使用sscanf函数
        if(!addnode(v,c))
        {
            flag=1;
        }
    }
    if(flag)
    {
        return 2;
    }
    return 1;
}
NODE *q[N];
int dfs()
{
    int l=0,r=1;
    q[0]=root;
    NODE *p;
    while(l<r)
    {
        p=q[l++];
        if(p->l!=NULL)
            q[r++]=p->l;
        if(p->r!=NULL)
            q[r++]=p->r;
        if(p->value==0)
            return 0;
    }
    for(int i=0; i<r; i++)
        cout<<q[i]->v<<" ";
    cout<<endl;
    return 1;
}
int main()
{
    freopen("ex.in","r",stdin);
    int flag=0;
    while((flag=input()))
    {
        if(flag==2)
            cout<<-1<<endl;//<<"chongfu"
        else if(!dfs())
            cout<<-1<<endl;//<<"wu zhi!"


    }


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值