ACM篇:Uva 122 -- Trees on the level

輸出末尾不能有空格。
坑。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int MAXN = 128;
char s[MAXN];
bool failed;

struct Node
{
    bool have_value;
    int val;
    Node *left;
    Node *right;
    Node() : have_value(false), left(NULL), right(NULL){}
};
Node *root = NULL;
void add_node(int val, char *str)
{
    Node *cur = root;
    while (*str != ')' && *str)
    {
        if (*str == 'L')
        {
            if (!cur->left)
                cur->left = new Node();
            cur = cur->left;
        }
        else if (*str == 'R')
        {
            if (!cur->right)
                cur->right = new Node();
            cur = cur->right;
        }
        str++;
    }
    if (cur->have_value)
        failed = true;
    cur->have_value = true;
    cur->val = val;
}
void remove_node(Node *u)
{
    if (!u)
        return;
    remove_node(u->left);
    remove_node(u->right);
    delete u;
}
bool read_input()
{
    failed = false;
    remove_node(root);
    root = new Node();
    while (true)
    {
        if (scanf("%s", s) != 1)
            return false;
        if (!strcmp(s, "()"))
            return true;
        int v;
        sscanf(s+1, "%d", &v);
        add_node(v, strchr(s, ',') + 1);
    }
}

void _print()
{
    queue<Node*> q;
    vector<int>ans;

    q.push(root);
    while (!q.empty() && !failed)
    {
        Node *head = q.front();
        q.pop();
        if (head->left)
            q.push(head->left);
        if (head->right)
            q.push(head->right);
        if (!head->have_value)
            failed = true;
        ans.push_back(head->val);
    }

    if (failed)
        printf("not complete\n");
    else
    {
        int sz = ans.size();
        for (int i = 0; i < sz; i++)
            printf("%d%s", ans[i], (i == sz-1) ? "\n" : " ");
    }
}
int main()
{
    while (read_input())
        _print();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章