zoukankan      html  css  js  c++  java
  • 6-7 树的层次遍历 uva122

    非常不熟练  照着书大的

    晚上尝试一下自己打  了解二叉树  用数组打

    第一次:

    #include<bits/stdc++.h>
    using namespace std;
    bool failed;
    
    
    void addnode(int v,char *s);
    char s[1000];
    struct node
    {
        bool  flag;
        int v;
         node *left,*right;
         node():flag(false),left(NULL),right(NULL){}
    
    };
    node *root;
    node *newnode(){return new node();}
    bool read_input()
    {
        failed=false;
        root=newnode();
        for(;;)
        {
            if(scanf("%s",s)!=1)return false;
            if(!strcmp(s,"()")) break;
            int v;
            sscanf(&s[1],"%d",&v);
            addnode(v,strchr(s,',')+1);
    
    
        }
        return true;
    
    }
    
    
    
    
    
    
    void addnode(int v,char *s)
    {
        int n=strlen(s);
        node *u=root;
        for(int i=0;i<n;i++)
        {
            if(s[i]=='L')
            {
                if(u->left==NULL)u->left=newnode();
                u=u->left;
    
            }
            else if(s[i]=='R')
            {
                if(u->right==NULL)u->right=newnode();
                u=u->right;
    
            }
    
        }
        if(u->flag)failed=true;
        u->v=v;
        u->flag=true;
    
    }
    
    bool bfs (vector<int>&ans)
    {
        queue<node*>q; ans.clear();
        q.push(root);
        while(!q.empty())
        {
            node *u=q.front();q.pop();
            if(!u->flag)return false;
            ans.push_back(u->v);
            if(u->left!=NULL)q.push(u->left);
            if(u->right!=NULL)q.push(u->right);
    
        }
        return true;
    
    
    }
    
    int main()
    {
    
       vector<int>ans;
       while(read_input())
       {
           if(!bfs(ans))failed=true;
           if(failed)printf("not complete
    ");
           else
           {
               for(int i=0;i<ans.size();i++)
               {
                   if(i==ans.size()-1)printf("%d
    ",ans[i]);
                   else printf("%d ",ans[i]);
    
               }
    
    
           }
    
    
       }
    
    
    
    
    
    
    
    
    
    
        return 0;
    }
    View Code
  • 相关阅读:
    redis 批量删除key
    控制台直接执行sql语句
    item2 快捷键
    mac mamp环境 PHP命令行反应缓慢解决
    composer gitlab 搭建私包
    PostgreSql命令
    maven 程序包com.sun.image.codec.jpeg
    lumen配置日志daily模式
    PHPStorm怎么修改选中的背景颜色呢?
    vim 配置文件.vimrc,高亮+自动缩进+行号+折叠+优化
  • 原文地址:https://www.cnblogs.com/bxd123/p/10288458.html
Copyright © 2011-2022 走看看