• 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;
    }
    
  • 相关阅读:
    把excel导入的自定义时间改成yyyyMMdd
    sql多表查询时怎么获取查到的字段
    select 和 input 的不可编辑,input隐藏
    关闭dialog(lhgdialog)
    ajax 和 post 传多个参数值具体怎么写
    弹出提示框,对话框
    function方法中this的用法
    combobox获取值
    easyui-panel 滚动条禁用
    字符串用逗号隔开;有逗号的字符串遍历
  • 原文地址:https://www.cnblogs.com/pengwill/p/7367119.html
Copyright © 2020-2023  润新知