UVA122

本题的基本思路就是先建树,然后在遍历二叉树,用线性表把数据存起来。

刘汝佳书中提到c语言字符串的灵活性,即把“指向字符的指针”看成字符串,下面的sscanf(&s[1],"%d",&v)中&s[1]即从s[1]开始的字符串。代码实现应该并不困难。

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1000;
int ans[MAXN],flot,k,v;
bool failed;
struct Node
{
    bool h_v;
    int v;
    Node *L,*R;
    Node():h_v(false),L(NULL),R(NULL) {}
}*head;//定义节点
void addnode(int v,char *s)
{
    Node *cur=head;
    for(int i=0;s[i];i++)
    {
        if(s[i]=='L')
        {
         	if(cur->L==NULL) cur->L=new Node();
         	cur=cur->L;
        }
        if(s[i]=='R')
        {
            if(cur->R==NULL) cur->R=new Node();
            cur=cur->R; 
        }
    }
    if(cur->h_v) failed=true;
    cur->v=v;
    cur->h_v=true;
}
void print()
{
    queue<Node *>q;
    Node *cur=head;
    q.push(head);
    while(!q.empty())
    {
        cur=q.front();
        q.pop();
        if(!cur->h_v) flot=0;
        if(!flot) break;
        ans[k++]=cur->v;
        if(cur->L!=NULL) q.push(cur->L);
        if(cur->R!=NULL) q.push(cur->R);
    }
    if(!failed&&flot)
    {
        for(int i=0;i<k;i++)
        {
        if(i) printf(" ");
        cout<<ans[i];
        }
    }
    else
    printf("not complete");
    puts("");
}
void freenode(Node *cur)
{
    if(cur==NULL) return ;
    freenode(cur->L);
    freenode(cur->R);
    free(cur);
}
int main()
{
    char s[MAXN];
    failed=false;
    head=new Node();
    while(~scanf("%s",s))
    {
        if(strcmp(s,"()")==0)
        {
            flot=1;
            k=0;
            print();
            freenode(head);
            head=new Node();
            failed=false;
            continue;
        }
        sscanf(&s[1],"%d",&v);
        addnode(v,strchr(s,',')+1);
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值