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);
   }
}



你可能感兴趣的:(uva122 Trees on the level(锻炼指针建一棵二叉树))