uva122

题目描述:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19630

/* 1:newNode()是个动态化静态的技巧 2:注意c语言字符串的灵活性,可以把任何“指向字符的指针”看成字符串 从该位置开始,直到结束符'\0' */
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>

using namespace std;

const int maxn = 256 + 10;

struct Node {
    int val;
    Node* left, *right;
    bool valued;
    Node() : left(NULL), right(NULL), valued(false) {}
};
Node * root;

Node* newNode() {
    return new Node();      //化动态方法为静态方法
}

void clear_tree(Node * n) {
    if(n == NULL)   return;
    clear_tree(n->left);
    clear_tree(n->right);
    delete n;
}

char cmd[maxn];
bool creat_failed;
bool make_tree() {      //创建一棵树
    creat_failed = false;
    clear_tree(root);
    root = newNode();   //new node
    while(true) {
        if(scanf("%s", cmd) != 1)   return false;
        if(!strcmp(cmd, "()"))  break;

        int v;
        sscanf(&cmd[1], "%d", &v);       //得到value值
        char * pos;
        pos = strchr(cmd, ',') + 1;       //得到节点位置(可以吧任意指向字符的指针看成字符串)

        //开始添加节点
        int len = strlen(pos);
        Node * r = root;
        for(int i = 0; i < len; i++) {
            if(pos[i] == 'L') {
                if(r->left == NULL)     r->left = newNode();
                r = r->left;
            }
            else if(pos[i] == 'R') {
                if(r->right == NULL)    r->right = newNode();
                r = r->right;
            }                                           //这里面忽略遇到“)”的情况
        }
        if(r->valued == true)   creat_failed = true;
        r->val = v;
        r->valued = true;

    }
    return true;
}

bool bfs(vector<int> &ans) {
    queue<Node*> q;
    ans.clear();
    q.push(root);

    while(!q.empty()) {
        Node* node = q.front();     q.pop();
        if(node->valued == false)   return false;
        ans.push_back(node->val);
        if(node->left != NULL)  q.push(node->left);
        if(node->right != NULL) q.push(node->right);
    }
    return true;
}

int main()
{
    vector<int> ans;    //用来存放节点的编号
    while(make_tree()) {
        ans.clear();
        if(!bfs(ans))   creat_failed = true;
        if(creat_failed) {
            printf("not complete\n");
        }
        else {
            for(int i = 0; i < ans.size(); i++) {
                if(i != 0) printf(" ");
                printf("%d", ans[i]);
            }
            printf("\n");
        }
    }
    return 0;
}

你可能感兴趣的:(uva122)