uva 112

#include <iostream>

using namespace std;

int a[100000];
int nLeaves;


typedef struct treeNode
{
    int data;
    treeNode*left,*right;
    treeNode():data(),left(NULL),right(NULL){}
    treeNode(int x):data(x),left(NULL),right(NULL){}

}treeNode;

inline bool isnum(char ch)
{
    return ((ch>='0' && ch<='9') || '-'==ch );
}
inline int ch2int(char ch)
{

    return (ch-48);
}

void createTree(treeNode*& root)
{
    char ch;
    int x=0;
    while(1)
    {
        ch=getchar();
        if(')'==ch)
        {
            return;
        }
        else if(isnum(ch))
        {
            x=0;
            int a=1;
            if('-'==ch)
            {
                a=-1;
                ch=getchar();
            }

            while(isnum(ch))
            {
                x=10*x+ch2int(ch);
                ch=getchar();
            }
            x*=a;

            root=new treeNode(x);
            createTree(root->left);
            createTree(root->right);
        }
    }
}
void destroyTree(treeNode* root)
{
    if(NULL==root)
        return ;
    destroyTree(root->left);
    destroyTree(root->right);
    delete root;
}

void getSum(treeNode*& root)
{
    if(NULL==root->left && NULL==root->right)
    {
        a[nLeaves++]=root->data;

    }
    if(NULL!=root->left)
    {
        root->left->data+=root->data;
        getSum(root->left);
    }
    if(NULL!=root->right)
    {
        root->right->data+=root->data;
        getSum(root->right);

    }
}

int main()
{

    treeNode* root;
    int pathSum;
    while (cin>>pathSum)
    {
        root=NULL;
        createTree(root);
        if(NULL==root)
        {
            cout<<"no"<<endl;
            continue;
        }
        nLeaves=0;
        getSum(root);
        bool flag=false;
        for (int i=0;i<nLeaves;i++)
        {
            if(a[i]==pathSum)
            {
                cout<<"yes"<<endl;
                flag=true;
                break;
            }
        }
        if(!flag)
            cout<<"no"<<endl;
        destroyTree(root);
    }
    return 0;
}

 

posted @ 2012-05-07 14:58  open your eyes  阅读(351)  评论(0编辑  收藏  举报