uva122 Trees on the level(锻炼指针建一棵二叉树)

题意:给你些字符串,按照他的要求,建议一颗二叉树,输出这课树的层次遍历。

思路:这棵树不是一颗完全二叉树,用数组建立,浪费内存,用指针建树,其中sscanf()函数作用很大,eg: sscanf(&s,"%d %d",&a,&b);在已有的字符串s中读取两个整形变量a,b;建好树后,再用广搜层次遍历。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
struct Node{
  bool used;
  Node *left,*right;
  int v;
  Node():used(false),left(NULL),right(NULL){}
};
Node *root;
char s[200];
bool failed;
Node *newnode(){ return new Node();}
void addnode(int v,char *s)
{
   Node *u=root;
   int n=strlen(s);
   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->used==true) failed=true;
     u->v=v;
     u->used=true;
}

bool read_input()
{
    failed=false;
    root=newnode();
    while(true){
        if(scanf("%s",s)!=1) return false;
        if(!strcmp(s,"()")) break;
        int v;
        char str[200];
        sscanf(s,"(%d,%s",&v,str);
        addnode(v,str);
     }
     return 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->used==NULL) 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;
}

void Delete(Node *t)
{
    if(t==NULL) return;
    Delete(t->left);
    Delete(t->right);
    delete t;
}

int main()
{
   vector<int>ans;
   while(read_input()){
     if(bfs(ans)&&!failed){
        for(int i=0;i<ans.size()-1;i++){
            printf("%d ",ans[i]);
        }
        printf("%d\n",ans[ans.size()-1]);
     }
     else{
        printf("not complete\n");
    }
    Delete(root);
   }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值