uva 112(二叉树)

题解:有模板。。先根据括号建树,然后用深搜存每条路径的和,最后循环对比,注意负数情况。

#include <stdio.h>
#include <string.h>
const int N = 10010;

struct Node {
    int val;
    Node* left;
    Node* right;
    Node () {
        val = 0;
        left = right = NULL;
    }
};

int k, sum[N];
void init() {
    k = 0;
    memset(sum, 0, sizeof(sum));
}
Node* build() {
    int flag = 0, flag1 = 0;
    Node* node = new Node;
    char c;
    while (scanf("%c", &c)) {
        if (c >= '0' && c <= '9')
            node -> val = node -> val * 10 + c - '0';
        else if (c == '(' && flag == 0) {
            node -> left = build();
            flag++;
        }
        else if (c == '(' && flag == 1)
            node -> right = build();
        else if (c == '-')
            flag1 = 1;
        else if (c == ')')
            break;
    }
    if (flag1)
        node -> val *= -1;
    if (flag == 0 && node -> val == 0)
        return NULL;
    else
        return node;
}

void dfs(Node* node, int s) {
    if (node == NULL)
        return;
    s += node -> val;
    if (node -> left == NULL && node -> right == NULL)
        sum[k++] = s;
    else {
        if (node -> left != NULL)
            dfs(node -> left, s);
        if (node -> right != NULL)
            dfs(node -> right, s);
    }
}

void Delete(Node* node) {
    if (node == NULL)
        return;
    if (node -> left != NULL)
        Delete(node -> left);
    if (node -> right != NULL)
        Delete(node -> right);
    delete node;
}
int main() {
    int n;
    char c;
    Node* root;
    while (scanf("%d", &n) != EOF) {
        init();
        while (scanf("%c", &c)) {
            if (c == '(') {
                root = build();
                break;
            }
        }
        dfs(root, 0);
        int i;
        for (i = 0; i < k; i++)
            if (sum[i] == n)
                break;
        if (i == k)
            printf("no\n");
        else
            printf("yes\n");
        Delete(root);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值