UVA122 - Trees on the level

尽量用的STL,运行效率有很大缺失,不过更容易理解,读者自行写C语言格式吧。

#include<iostream>
#include<cstdio>
#include<malloc.h>
#include<string>
#include<sstream>
#include<queue>
using namespace std;
struct Node{
    bool have_value;
    int v;
    Node *left, *right;
    Node() :have_value(0) ,left(NULL),right(NULL){}
};

Node *newnode(){
    Node *u=(Node *)malloc(sizeof(Node));
    u->have_value=0;
    u->left=NULL;
    u->right=NULL;
    return u;
}

Node *head;
int failed;

void addnode(int v,string s){
    Node *u=head;
    for(string :: iterator t=s.begin();t !=s.end(); t++){
        if(*t=='L'){
            if(u->left == NULL) u->left=newnode();
            u= u->left;
        }
        else if(*t=='R'){
            if(u->right == NULL) u->right=newnode();
            u= u->right;
        }
    }
    if(u->have_value==1) (failed = 1);//cout<<"=";
    u->have_value = 1;
    u->v = v;
}

vector<int> ans;

int bfs(vector<int> &ans){
    queue<Node*> q;
    ans.clear();
    q.push(head);
    while(!q.empty()){
        Node* u =q.front(); q.pop();
        if(!u->have_value) return 1;//错了
        ans.push_back(u->v);
        if(u->left!=NULL) q.push(u->left);
        if(u->right!=NULL) q.push(u->right);
    }
    return 0;
}

void remove_tree(Node* u) {
  if(u == NULL) return;
  remove_tree(u->left);
  remove_tree(u->right);
  free(u);
}

int input(){
    remove_tree(head);
    head=newnode();
    failed=0;
    string s,key;
    while(cin>>s){
        if(s=="()") return 1;
        int value;
        for(unsigned i =0; i<s.length(); i++)
            if(s[i]=='('||s[i]==',') s[i]=32;
        stringstream ss(s);
        ss>>value>>key;
        //cout<<value<<" "<<key<<endl;//
        addnode(value,key);
        //cout<<"="<<endl;
    }
    return 0;
}

int main(){
    while(input()){
        vector<int> q;
        bfs(q)&&(failed=1);
        if(failed) cout<<"not complete"<<endl;
        else{
            for(unsigned i =0;i<q.size(); i++){
            if(i) cout<<" ";
                cout<<q[i];
            }
            cout<<endl;
        }
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值