// UV problem 112-tree summing // verdict: accepted // submission date: 2011-11-26 // UV Run Time: 0.304 S // copyright (c) qiu, 2011. Metaphysis # Yeah dot net // [solution] // This question can be attributed to a data structure problem. //// Use a linked list to represent the tree. If an array is used, the array may be too large because of the large depth of the tree. The key is how to resolve the input to a chain table/display tree. This topic is resolved with the help of CIN. putback. After the resolution is complete, the rest is the problem of tree traversal. # Include <iostream> # include <cstdlib> using namespace STD; struct node {struct node * parent; struct node * leftchild, * rightchild; int value ;}; bool havetargetsum, emptytree; // Save the path to the leaf node. Void summingtree (node * Current) {If (current-> leftchild! = NULL) {current-> leftchild-> value + = Current-> value; summingtree (current-> leftchild);} If (current-> rightchild! = NULL) {current-> rightchild-> value + = Current-> value; summingtree (current-> rightchild) ;}// uses cin. putback () to recursively parse the tree. Void parsetree (node * Current) {bool isleaf = false; char C; while (CIN> C, C! = '('); // Negative values must be considered. Cin> C; If (isdigit (c) | C = '-') {int Sign = (C = '-'? (-1): 1); int number; If (isdigit (c) number = C-'0'; elsenumber = 0; while (CIN> C, isdigit (c) {Number * = 10; Number + = (c-'0');} cin. putback (c); current-> value = Number * sign;} else {cin. putback (c); // if the current node is empty, the corresponding child node of the parent node is empty. If (current-> parent! = NULL) {If (current = Current-> parent-> leftchild) Current-> parent-> leftchild = NULL; elsecurrent-> parent-> rightchild = NULL ;} elseemptytree = true; isleaf = true;} // if it is not a leaf node, the Child tree will be parsed. If (! Isleaf) {node * Left = new node; Current-> leftchild = left; left-> parent = current; parsetree (left); node * Right = new node; current-> rightchild = right; right-> parent = current; parsetree (right);} while (CIN> C, C! = ');} // Traverse the tree and check whether the path saved by the leaf node is the target value. Void traveltree (node * Current, int targetsum) {If (havetargetsum) return; If (current-> leftchild = NULL & Current-> rightchild = NULL) if (current-> value = targetsum) havetargetsum = true; If (current-> leftchild! = NULL) traveltree (current-> leftchild, targetsum); If (current-> rightchild! = NULL) traveltree (current-> rightchild, targetsum);} int main (INT argc, char const * argv []) {int targetsum; while (CIN> targetsum) {node * root = new node; emptytree = false; parsetree (Root); summingtree (Root); havetargetsum = false; If (! Emptytree) traveltree (root, targetsum); cout <(havetargetsum? "Yes \ n": "No \ n"); Delete root;} return 0 ;}