uva 122

#include <iostream>
#include <vector>
#include <cstdio>
#include <queue>
using namespace std;
struct node{
    bool vis;
    int val;
    node *l, *r;
    node():vis(false), l(NULL), r(NULL){}
};
node* newnode(){
    return new node();
}
node *root;
int flag;
void addnode(int v, int q, string s)
{
    int len = s.size();
    node* u = root;
    for(int i = q; i < len; i++){
        //cout << s[i] << " ";
        if(s[i] == 'L'){
            if(u -> l == NULL){
                u -> l = newnode();
            }
            u = u -> l;
        } else if(s[i] == 'R'){
            if(u -> r == NULL) u -> r = newnode();
            u = u -> r;
        }
    }
    if(u -> vis) flag = 1;
    u -> val = v;
    u -> vis = true;
}
vector <int> ans;
bool bfs()
{
    queue<node*> q;
    ans.clear();
    q.push(root);
    while(!q.empty()){
        node *u = q.front();
        q.pop();
        if(!u -> vis) return false;
        ans.push_back(u -> val);
        //cout << u -> val << endl;
        if (u->l != NULL)q.push(u->l);
        if (u->r != NULL)q.push(u->r);
    }
    return true;
}
int main()
{
    size_t q;
    string s;
    root = new node();
    while(cin >> s)
    {
        if(s == "()"){
//            if(bfs() == false) cout << "here1";
//            if(flag) cout << "here2";
            if(bfs() == false || flag) cout << "not complete" << endl;
            else{
                int len = ans.size();
                for(int i = 0; i  < len; i++){
                    if(i == len - 1) cout << ans[i] <<endl;
                    else cout <<ans[i] << " ";
                }
            }
            flag = 0;
            root = new node();
           // cout << flag << endl;
        } else{
            int v;
            sscanf(&s[1], "%d", &v);
            int q = s.find(',');
            addnode(v, q+1, s);
        }
    }

}
哇 这个模拟总算写出来了,纪念一发, 这个题里用了string的find , sscanf真的挺好用的。。还兼容string, 要注意多组数据的更新, 本程序并未处理紫书上说的 内存泄漏以后在改吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值