刘汝佳第六章UVA-122

用结构体实现了不完全二叉树

  1. 用到了不熟悉的构造函数
  2. 多个模块分开写成函数
  3. 用了几个str的操作
  4. 队列实现BFS,vectro储存结果
  5. 注意输出not complete 的情况,要考虑周全,然后用一个failed来判断。
  6. 用数组来表示这种数据结构也行。
#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<cstdlib>
using namespace std;
const int MAX=20;
bool failed;
char s[MAX];
vector<int> ans;

struct Node
{
    bool have_value;
    int v;
    Node *left,*right;
    Node():have_value(false),left(NULL),right(NULL){};//构造函数
};


Node *newnode()
{
    return new Node();  //申请内存,再用构造函数,封装再newnode这个函数里面.
}


Node* root=newnode();

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;
        }
        if(s[i]=='R')
        {
            if(u->right==NULL)
                u->right=newnode();
            u=u->right;
        }
//        printf("the value of have_value is%d\n",u->have_value);
    }
//    printf("%d",failed);
    if(u->have_value==true) failed = true;
//     printf("%d",failed);
    u->v=v;
    u->have_value=true;

}


bool read_input()
{
    failed = false;
    while(1)
    {
//            printf("1\n");
        if (scanf("%s",s)==EOF)
            return false;
        else
        {
            if(!strcmp(s,"()"))
                break;
            int v;
            sscanf(s+1,"%d",&v);
            addnode(v,strchr(s,',')+1);  //这里不用特意再储存一个pos字符串,可以直接用s里面的地址,反正最后都是'\0'结尾,在addnode里面使用strlen(s)就可以了
        }
    }
    return true;
}





bool bfs(vector<int> &ans) //队列实现BFS
{
      queue<Node*> q;
      ans.clear();
      q.push(root);
      while(!q.empty())
      {
            Node *u=q.front();
            q.pop();
            if(!u->have_value)
            {
              failed=true;
              return false;
            }
            ans.push_back(u->v);
            if(u->left) q.push(u->left);
            if(u->right)q.push(u->right);
      }
      return true;
}


int main(void)
{
    while (1)
    {
    if(read_input()==0)
        return 0;
//    printf("1\n");
    bfs(ans);
    if(failed)
    {
        printf("not complete");
        return 0;
    }
    for (int i=0;i<ans.size();i++)
        printf("%d ",ans[i]);
    printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值