UVA122 二叉树的链式表示法

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<vector>
#include<queue>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
const int maxn=300;
char s[maxn];
bool failed;
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();
}
node* root;
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->have_value)
        failed=true;
    u->v=v;
    u->have_value=true;    
}
void remove_tree(node* u)
{
    if(u==NULL)
        return;
    remove_tree(u->left);
    remove_tree(u->right);
    delete u;
}
bool bfs(vector<int>& ans)
{
    queue<node*>q;
    ans.clear();
    q.push(root);
    while(!q.empty())
    {
        node* u=q.front();
        q.pop();
        if(!u->have_value)
            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 printf_out()
{
    for(int i=0;i<ans.size();i++)
    {
        if(i)
            printf(" %d",ans[i]);
        else 
            printf("%d",ans[i]);
    }
    printf("\n");
}
bool read_input()
{
    failed=false;
    remove_tree(root);
    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;
}
int main()
{
    while(read_input())
    {
        bfs(ans);
        if(failed||!bfs(ans))
            printf("not complete\n");
        else 
            printf_out();
    }
    return 0;
}

 

posted @ 2016-10-16 17:36  web之路  阅读(119)  评论(0)    收藏  举报