uva_112_Tree Summing

来源:互联网 发布:国外个人java技术博客 编辑:程序博客网 时间:2024/06/05 00:26
#include <cstdio>#include <cctype>#include <cstring>#include <algorithm>using namespace std;#define MAXN    1001typedef 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;}

原创粉丝点击