UVA 122 例题 6-7

根据紫书,与vjudge上的大佬的代码写出来的代码,惭愧!!

PS:
udebug尽管比较好,但是其中的样例不一定是对的,本题udebug中得到的结果并不对,不可ac。

经典建树的题,可以分为几个方面:

  • 节点的各个信息 struct node
  • 创立新节点 node * newnode()创建新节点,并返回其指针
  • 添加新节点, 节点不存在时,创建新节点,存在时,跳过
  • 用BFS遍历,queue来存每一层的节点的指针,并以此来输出需要输出的值,按层遍历。
#include <iostream>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
vector<int>v;
bool failed=false;
struct node
{
    bool have_value;
    int value;
    node *left,*right;
    node():have_value(false),left(NULL),right(NULL){}//构造函数
};

node *root;//创立根节点


node *newnode()//创建新节点并返回地址。
{
    return new node;
}


void addnewnode(int x,char *c)
{
    int n=strlen(c);
    node *r=root;
    for(int i=0;i<n;i++)
    {
        if(c[i]=='L')
        {
            if(r->left==NULL) r->left=newnode();
            r=r->left;
        }
        else if(c[i]=='R')
        {
            if(r->right==NULL) r->right=newnode();
            r=r->right;
        }
    }
    if(r->have_value) failed=true;
    r->value=x;
    r->have_value=true;


}

bool bfs(vector<int>&v)
{
    v.clear();
    queue<node*>q;
    q.push(root);
    while(!q.empty())
    {
        node* r=q.front();
        q.pop();
        if(!r->have_value)
            return false;

        if(r->left!=NULL) q.push(r->left);
        if(r->right!=NULL) q.push(r->right);
        v.push_back(r->value);
    }
    return true;

}
int main()
{
   // freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    while(1)
    {
        char s[200000];
        failed=false;
        root=newnode();
        while(1)
        {
            int num;
            if(scanf("%s",s)!=1) return 0;
            if(!strcmp(s,"()")) break;
            sscanf(&s[1],"%d",&num);
            addnewnode(num,strchr(s,',')+1);
        }
        bfs(v);

        if(!root->have_value) failed=true;
        if(failed)
           cout<<"not complete"<<endl;
        else
        {
            for(int i=0;i<v.size();i++)
            {
                if(i!=0)
                    cout<<" ";
                cout<<v[i];
            }
            cout<<endl;
        }
    }
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值