Uva_112-Tree (Summing)

Source: Internet
Author: User

[Cpp]
/** The difficulty of this question lies in the creation. Because the input may not be in one row, it cannot be received using strings.
* It must be read one by one. Here, getchar () is used (of course, scanf is also used ).
* '(', Start to receive data. If it is ')', the subtree is empty; otherwise, it is a number (possibly
* Negative number), here is a note that space, also pitted me for a long time, did not think of windows
* Differences with linux, and finally solved by using the library function isspace...
*/
# Include <cstdio>
# Include <cctype>
Using namespace std;
 
Struct Node {
Int v;
Node * lc, * rc;
};
 
Bool flag;
 
Void pre_create_tree (Node * & root ){
Char c;
Int v = 0, leap = 0;
If (! Flag) while (getchar ()! = '(');
While (c = getchar ()){
If (isspace (c) continue;
If (c = '(' | c = ') break;
If (c = '-') {leap = 1; continue ;}
V * = 10;
V + = c-'0 ';
}
If (')' = c ){
Root = NULL;
Flag = false;
}
Else {
Flag = true;
If (leap) v =-v;
Root = new Node;
Root-> v = v;
Pre_create_tree (root-> lc );
Pre_create_tree (root-> rc );
}
}
 
Void pre_traverse (Node * root, int ans ){
If (flag) return;
If (! Root) return;
Ans-= root-> v;
If (root-> lc) pre_traverse (root-> lc, ans );
If (root-> rc) pre_traverse (root-> rc, ans );
If (! Ans &&! Root-> lc &&! Root-> rc) flag = true;
}
 
Int main (int argc, char const * argv []) {
# Ifndef ONLINE_JUDGE
Freopen ("test. in", "r", stdin );
# Endif
Int ans, c;
While (~ Scanf ("% d", & ans )){
Node * root;
Flag = false;
Pre_create_tree (root );
While (c = getchar ()){
If (c = '\ n') break;
If (c = EOF) break;
}
Pre_traverse (root, ans );
If (flag) printf ("yes \ n ");
Else printf ("no \ n ");
 
}
Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.