• UVA.122 Trees on the level(二叉树 BFS)


    UVA.122 Trees on the level(二叉树 BFS)

    题意分析

    给出节点的关系,按照层序遍历一次输出节点的值,若树不完整,则输出not complete

    代码总览

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    #include <vector>
    #define nmax 10000
    using namespace std;
    bool failed;
    struct node{
        bool isvalue;
        node * left, *right;
        int val;
        node():isvalue(false),left(NULL),right(NULL){}
    };
    node* root;
    //node* roott;
    char s[nmax];
    node* newnode()
    {
        return new node();
    }
    bool addnode( int v, char * str)
    {
        int len = strlen(str);
        node*t = root;
        for(int i = 0; i<len; ++i){
            //if(len == 1)
            if(str[i] == 'L'){
                if(t->left == NULL) t->left = new node();
                t = t->left;
            }else if(str[i] == 'R'){
                if(t->right == NULL) t->right = new node();
                t = t->right;
            }
        }
        if(t->isvalue == true) failed = true;
        t->val = v;
        t->isvalue = true;
        return true;
    }
    bool read_input()
    {
        failed = false;
        root = newnode();
        for(;;){
            if(scanf("%s",s) !=1) return false;
            else{
                int v;
                if(!strcmp(s,"()")) break;
                sscanf(&s[1],"%d",&v);
                addnode(v,strchr(s,',')+1);
            }
        }
        return true;
    }
    
    bool bfs(vector<int> & ans)
    {
        queue<node*> q;
        ans.clear();
        q.push(root);
        while(!q.empty()){
            node* t = q.front();q.pop();
            if(t ->isvalue == false ) {failed = true; break;}
            ans.push_back(t->val);
            if(t){
                if(t->left)q.push(t->left);
                if(t->right)q.push(t->right);
            }
        }
        return true;
    
    }
    int main()
    {
        //freopen("in.txt","r",stdin);
        vector<int> ans;
        //roott = newnode();
        while(read_input()){
            bfs(ans);
            if(failed) printf("%s
    ","not complete");
            else{
                bool flag = false;
                for(int i = 0; i<ans.size();++i){
                    if(i == 0) printf("%d",ans[i]);
                    else printf(" %d",ans[i]);
                }
                printf("
    ");
            }
        }
        return 0;
    }
    
  • 相关阅读:
    转 linux设备模型(4)
    SQL convert
    SQL 中的 case when
    自己写的文本文件加密器
    [A3] 2D Airfoil Aerodynamic Analysis With Fluent & Gambit
    [A2]更快的使用你的键盘:AutoHotkey
    [A4]更快的使用你的键盘:AutoHotkey(2)
    开篇HOG提取训练检测+样本制作
    Flash调用Lua脚本: 五
    Sql Server全局变量 【转载】
  • 原文地址:https://www.cnblogs.com/pengwill/p/7367119.html
Copyright © 2020-2023  润新知