UVa122

#pragma warning(disable:4996)
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#include<algorithm>
#include<iostream>
#include<time.h>
#include<set>
#include<sstream>
#include<functional>
#include<cassert>
#include<list>
#include<iterator>
#include<utility>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include<ctype.h>
#include<map>
#include<stack>
#include<queue>
#include<cstdlib>

using namespace std;

const int maxn = 256 + 10;

bool failed;

struct Node {
    int v;
    Node* left, *right;
    Node() :left(NULL), right(NULL),v(0) {}
};

Node* newNode() { return new Node(); }
Node* root;

int rootflag = 0;
int cnt;
void remove_tree(Node* u)
{
    if (u == NULL)return;
    remove_tree(u->left);
    remove_tree(u->right);
    delete u;
}
void addNode(int v, char* str)
{
    if (!strcmp(str, ")"))
        rootflag = 1;
    Node* u;
    u = root;
    for (int i = 0;i < strlen(str)-1;i++)
    {
        if (str[i] == 'L')
        {
            if (!u->left)u->left = newNode();
            u = u->left;
        }
        else
        {
            if (!u->right)u->right = newNode();
            u = u->right;
        }
    }
    if (u->v)
        failed = true;
    u->v = v;
}


bool input_read()
{
    remove_tree(root);
    cnt = 0;
    rootflag = 0;
    int v;
    failed = false;
    root = newNode();
    char str[maxn];
    for (;;)
    {
        cnt++;
        if (scanf("%s", str) != 1)return false;
        if (!strcmp(str, "()"))
            break;
        sscanf(&str[1], "%d", &v);
        addNode(v, strchr(str, ',') + 1);
    }
    return true;
}

void print(vector<int> &ans)
{
    queue<Node*> q;
    ans.clear();
    q.push(root);
    while (!q.empty())
    {
        Node* u = q.front();q.pop();
        if (!u->v)
        {
            cout << "not complete" << endl;
            return;
        }
        ans.push_back(u->v);
        if (u->left!=NULL)q.push(u->left);
        if (u->right!=NULL)q.push(u->right);
    }
    if (ans.size() != (cnt-1) || failed)
        cout << "not complete" << endl;
    else
    {
        for (int i = 0;i < ans.size()-1;i++)
            cout << ans[i] << " ";
        cout << ans[ans.size() - 1];
        cout << endl;
    }
}

int main()
{
    while (input_read())
    {
        vector<int> ans;
        print(ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jack_jyh/article/details/53310962
122