112-tree Summing
Time limit:3.000 seconds
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=48
Background
LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages being used. Lists, which are the fundamental data structures in LISP, can easily is adapted to represent other important data structur Es such as trees.
This problem deals with determining whether binary trees represented as LISP s-expressions a possess property.
The Problem
Given a binary tree of integers, your are to write a program that determines whether there exists a root-to-leaf path whose Nodes sum to a specified integer. For example, in the shown below there are exactly four root-to-leaf paths. The sums of the paths are, and 18.
Binary trees are represented in the input file as LISP S-expressions has the following form.
Empty tree :: = ()
Tree:: = Empty tree (An integer tree)
The tree diagrammed above are represented by the expression (5 (4 (11) (7 () ()) (2 () ()) ()) (8 () () ()) (13 () (4 ()) ( )) ) ) )
This is formulation all leaves the "a" tree are of the form (Integer () ())
Since an empty the has no root-to-leaf paths, any query as to whether a path exists whose the sum of a specified integer in a n Empty tree must is answered negatively.
The Input
The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists of the followed by one or over spaces followed by a binary tree formatted as a S-expressio N as described above. All binary tree s-expressions is valid, but expressions may is spread over several lines and may contain spaces. There'll be one or more test cases in a input file, and the input is terminated by End-of-file.
The Output
There should is one line of output for each test case (Integer/tree pair) in the input file. For each pairi,t (I represents the integer, T represents the "tree") the output is the string yes if there is a root-to-leaf Path in T whose the sum is I and no if there are no path in t whose the sum is I.
Sample Input
(5 (4 (7 () ()) (2 () ()) ()) (8 () ()) (4 () (1 () ())))
20 (5 (4 (11 (7 () ()) (2 () ())) ()) (8 (13 () ()) (4 () (1 () ())))
3
(2 (4 () ())
(8 () ()))
(1 (6 () ())
(4 ()
())) 5 ()
Sample Output
Yes
no
Yes
no
Look at the code and you'll understand.