这个题目考的就是仔细程度,树结点为空必须赋为null,因为ans可能为0呵呵,就是这个让我wa的好多次(我将空结点的数值全赋为0),还有就是负数的问题了(这个我是想到了的,嘿嘿) #include <iostream> #include <cstring> #include <cstdlib> using namespace std ; const int maxn = 10000 + 10 ; struct Node { Node * left ; Node * right ; int data ; } ; char chstack[maxn] ;//字符栈 Node * Stack[maxn] ;//结点栈 int topc , topn ; int count1 , count2 , countc ; char str[maxn] ; int ok ; //初始化 void init() { topc = 0 ; topn = 0 ; ok = 0 ; memset( chstack , 0 , sizeof( chstack ) ) ; memset( Stack , 0 , sizeof( Stack ) ) ; memset( str , 0 , sizeof( str ) ) ; count1 = 0 ; count2 = 0 ; countc = 0 ; return ; } void input() { //读入数据,只要数,括号和负号 int flag = 0 ; while( 1 ) { char ch = getchar() ; if( ch =='(' ) { flag = 1 ; count1++ ; str[countc++] = ch ; } if( isdigit( ch ) || ch == '-' ) { str[countc++] = ch ; } if( ch == ')' ) { count2++ ; str[countc++] = ch ; } if( count1 == count2 && flag ) break ;//如果前括号与后括号的数量相同,并且进入过括号,读入数据结束 } return ; } void change( char s[] , int len ) { char ts[1000] ; int j = 0 ; for( int i = len - 1 ; i >= 0 ; i-- ) ts[j++] = s[i] ; strcpy( s , ts ) ; s[j] = '/0' ; return ; } Node * addNode( int data , Node * left , Node * right )//往树上添加结点 { Node * father = new Node ; father -> left = left ; father -> right = right ; father -> data = data ; return father ; } void buildTree()//建树 { int len = strlen( str ) ; for( int i = 0 ; i < len ; i++ ) { if( str[i] == ')' )//当遇到后括号时,找前一个前括号,前且创建结点入栈 { char node[1000] ; int c = 0 ; memset( node , 0 , sizeof( node ) ) ; while( chstack[topc] != '(' ) { node[c++] = chstack[topc--] ; } topc-- ; change( node , c ) ; int num = ( int )atof( node ) ; if( strlen( node ) ) { Node * right = Stack[topn--] ; Node * left = Stack[topn--] ; Node * father = addNode( num , left , right ) ; Stack[++topn] = father ; } else { Node * p = new Node ;//如果是空结点(前括号与后括号相邻),创建空结点 p = NULL ; Stack[++topn] = p ; } } else chstack[++topc] = str[i] ;//不是后括号,入字符栈 } return ; } void dfs( int ans , int cur , Node * u ) { if( u != NULL )//当结点不为空 { cur += u -> data ; //当到达树的最底部,并且和与ans相当,说明找到答案 if( cur == ans && ! ( u -> left) && ! ( u -> right ) ) { ok = 1 ; return ; } else { if( u -> left ) dfs( ans , cur , u -> left ) ;//递归左子树 if( u -> right ) dfs( ans , cur , u -> right ) ;//递归右子树 } } } int main() { int ans ; while( cin >> ans ) { init() ; input() ; buildTree() ; Node * root = Stack[topn] ;//树根是结点栈顶部的元素 dfs( ans , 0 , root ) ; if( ok ) cout << "yes" << endl ; else cout << "no" << endl ; } return 0 ; }