UVA 122(二叉树+字符串输入)

题意:

给你一颗二叉树上面的若干节点上的值(均为正数),判断从根到所有的给定的点的路径上的节点,是不是都有值,且只被赋值一次。

思路:这题不难,主要是一些细节上的处理,学习一下。。

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=200005;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
struct node
{
    int v;
    bool have_value;
    node *left,*right;
    node():have_value(false),left(NULL),right(NULL) {}
};
node *root;
bool fail;
node *newnode()
{
    return new node();
}
char s[1000];
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)
        fail=true;
    u->v=v;
    u->have_value=true;
}
bool read()
{
    fail=false;
    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;
}
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)
            q.push(u->left);
        if(u->right)
            q.push(u->right);
    }
    return true;
}
int main()
{
    while(1)
    {
        root=newnode();
        if(!read())
            break;
        vector<int> ans;
        if(!fail&&bfs(ans))
        {
            int len=ans.size();
            for(int i=0; i<len; i++)
            {
                printf("%d%c",ans[i],i==len-1?'\n':' ');
            }
        }
        else
        {
            puts("not complete");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dilly__dally/article/details/82261077
今日推荐