uva112-树求和

此题小白书数据结构基础二叉树的训练参考

 

翻译请戳 http://luckycat.kshs.kh.edu.tw/

 

解题思路

建树。如果遇到'('并能找到数字就建立相应的根节点,再递归建立左子树和右子树。

空子树的判断要单独拿出来。子树建完后记得把')'也给吃掉。

有许多空格和换行,判断并忽略它们就行了。

 

最后要得到相应的路径值,只需要BFS整棵树就行。

 

代码

#include<stdio.h>
#define MAX_SIZE 10000
//#define LOCAL
typedef struct node {
    int value, sum;
    struct node *lchild, *rchild;
}Node;
Node *q[MAX_SIZE];
void build(Node *&root)
{
    char c;
    while((c=getchar())==' '||c=='\n') ;
    //ungetc(c, stdin);
    if(c == ')') return ;
    else if(c == '(') {
        while((c=getchar())==' '||c=='\n') ;
        if(c == ')') return ;
        else {
            int d;
            ungetc(c, stdin);
            scanf("%d", &d);
            root = new Node;
            root->value = d; root->sum = d;
            root->lchild = NULL; root->rchild = NULL;
            build(root->lchild);
            while((c=getchar())!='(') ;
            ungetc(c, stdin);
            build(root->rchild);
            while((c=getchar())!=')') ;
        }
    }
}
bool GetSum(Node *root, int target)
{
    int front, rear;
    front = rear = -1;
    root->sum = root->value;
    q[++rear] = root;
    while(front != rear) {
        Node *u = q[++front];
        if(u->lchild != NULL) {
            q[++rear] = u->lchild;
            q[rear]->sum += u->sum;
            if(q[rear]->lchild==NULL && q[rear]->rchild==NULL)
                if(q[rear]->sum == target) return true;
        }
        if(u->rchild != NULL) {
            q[++rear] = u->rchild;
            q[rear]->sum += u->sum;
            if(q[rear]->lchild==NULL && q[rear]->rchild==NULL)
                if(q[rear]->sum == target) return true;
        }
        if(u->rchild==NULL&&u->lchild==NULL&&u->sum==target) return true;
    }
    return false;
}
int main()
{
    #ifdef LOCAL
        freopen("data.txt", "r", stdin);
        freopen("ans.txt", "w", stdout);
    #endif
    int ch;
    ch = getchar();
    while(ch != EOF) {
        int target;
        Node *root = NULL;
        ungetc(ch, stdin);
        scanf("%d", &target);
        build(root);
        if(root == NULL) printf("no\n");
        else if(GetSum(root, target)) printf("yes\n");
            else printf("no\n");
        while((ch=getchar())!='\n') ;
        ch = getchar();
    }
    return 0;
}

 

posted @ 2016-08-08 21:49  啊嘞  阅读(610)  评论(0编辑  收藏  举报