uva122_TreesOnTheLevel

#include <iostream>
#include<string>
#include<vector>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;

const int maxn = 256 + 10;

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

bool addNode(int val, char* s)
{
    int len = strlen(s) - 1;
    Node* u = root;
    for(int i = 0; i < len; i++){
        if(s[i] == 'L'){
            if(u->left == NULL)
                u->left = new Node();
            u = u->left;
        }else if(s[i] == 'R'){
            if(u->right == NULL)
                u->right = new Node();
            u = u->right;
        }
    }
    if(u->has_value) return false;
    u->val = val;
    u->has_value = true;
    return true;
}

bool ok;
bool readData()
{
    root = new Node();
    char s[maxn];
    ok = true;
    while(1){
        int res = scanf("%s", s);
        if(res == EOF) return false;
        if(strcmp(s, "()") == 0) break;
        if(ok == false)
            continue;
        int val;
        sscanf(s + 1, "%d", &val);
        if(addNode(val, strchr(s, ',') + 1) == false){
            cout << "ffffffffffffffffffff" << endl;
            ok = false;
        }

    }
    return true;
}



bool dfs(Node* u)
{
    if(u == NULL)
        return true;
    if(dfs(u->left) && dfs(u->right) && u->has_value)
        return true;
    return false;
}

void bfs()
{
    queue<Node*>q;
    q.push(root);
    bool first = true;
    while(!q.empty()){
        Node* u = q.front(); q.pop();
        if(first){
            cout << u->val;
            first = false;
        }else
            cout << " " << u->val;
        if(u->left){
            q.push(u->left);
        }
        if(u->right){
            q.push(u->right);
        }
    }
    cout << endl;
}
void solve()
{
    cout << "ok" << ok << endl;
    if(!ok || !dfs(root)){
        cout << "not complete\n";
    }else{
        bfs();
    }
}
int main()
{
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    while(readData()){
        solve();
    }
    return 0;
}

 

题意:按照某种格式给定一棵二叉树的,层次遍历一下。

分析:二叉树、建树、层次遍历。

收获:

1.  如果EOF为输入结束标志 并且 每组数据需要多次读取,可以将一组数据的输入封装成一个函数,大致框架如下:

  

bool readData()
{
    while(true){
        if(scanf() == EOF) return false;
        if(本组数据结束) break;
        ...
    }
    return true;
}

int main()
{
  while(readData()){
    solve();
  }
  return 0;
}

  

2. 此题一开始maxn = 256,作为输入缓冲区的大小,但256仅仅是L、R的最大个数,还包括(、)、,、\0,这样将导致无法通过正好256个节点连成一条线的情况。

posted on 2019-02-19 15:16  nbsanshi  阅读(124)  评论(0编辑  收藏  举报

导航