uva_112_Tree Summing

#include <cstdio>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;

#define MAXN    1001

typedef struct _BTREENODE {
        int data;
        struct _BTREENODE *left_child;
        struct _BTREENODE *right_child;
}BTREENODE;

char ch, num[MAXN/100];
int stack[MAXN], s_pos, flag;

void get_node_data(BTREENODE **node)
{
        if( !s_pos ) {
                (*node) = NULL; return;
        }
        int idx(0), mark(0), val;
        while( ~scanf("%c", &ch) && s_pos ) {
                if( '(' == ch ) {
                        stack[s_pos ++] = ch; mark ++;
                }
                else if( ')' == ch ) {
                        s_pos --;
                }
                else if( '-' == ch || isdigit(ch) ) {
                        num[idx ++] = ch;
                }
                if( mark ) {
                        if( idx ) {
                                num[idx] = '\0'; sscanf(num, "%d", &val);
                        }
                        break;
                }
        }
        if( !idx ) {
                (*node) = NULL; return;
        }
        (*node) = new BTREENODE; (*node)->data = val;
        get_node_data(&(*node)->left_child);  get_node_data(&(*node)->right_child);
}

void pre_order(BTREENODE *node, int cur_sum, const int &search_key)
{
        if( NULL == node || flag ) {
                return;
        }
        if( NULL == node->left_child && NULL == node->right_child && 
            cur_sum+node->data == search_key ) {
                flag = 1; return;
        }
        pre_order(node->left_child, cur_sum+node->data, search_key);
        pre_order(node->right_child, cur_sum+node->data, search_key);
}

int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
        freopen("test.in", "r", stdin);
#endif
        int search_key;
        BTREENODE *root;
        while( ~scanf("%d", &search_key) ) {
                while( scanf("%c", &ch) && '(' != ch ) {}
                s_pos = 0; stack[s_pos ++] = ch; flag = 0;
                get_node_data(&root); pre_order(root, 0, search_key);
                if( flag ) {
                        printf("yes\n"); continue;
                }
                printf("no\n");
        }
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值