LISP was one of the earliest highlevel programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, which are the fundamental data structures in LISP, can easily be adapted to represent other important data structures such as trees. This problem deals with determining whether binary trees represented as LISP Sexpressions possess a certain property.
Given a binary tree of integers, you are to write a program that determines whether there exists a roottoleaf path whose nodes sum to a specified integer. For example, in the tree shown below there are exactly four roottoleaf paths. The sums of the paths are 27, 22, 26, and 18.
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Binary trees are represented in the input file as LISP Sexpressions having the following form:
EmptyTree ::= '()'
Tree ::= EmptyTree  '(' Integer Tree Tree ')'
Note that with this formulation all leaves of a tree look similar to this (note that the space characters are irrelevant):
( 42 () () )
Since an empty tree has no roottoleaf paths, any query as to whether a path exists whose sum is a specified integer in an empty tree must be answered negatively.
The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists of an integer followed by one or more spaces followed by a binary tree formatted as an Sexpression as described above. All binary tree Sexpressions will be valid, but expressions may be spread over several lines and may contain spaces. There will be one or more test cases in an input file, and input is terminated by endoffile.
There should be one line of output for each test case (integer/tree pair) in the input file. For each
pair \((I, T)\) of an integer and a tree in the input, the output is the string yes
if there is a roottoleaf path in \(T\) whose sum is \(I\) and no
if there is no such path in.
22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3
(2 (4 () () )
(8 () () ) )
(1 (6 () () )
(4 () () ) ) )
5 ()
yes
no
yes
no
This is challenge 112 of the ACM International Collegiate Programming Contest. Test input is provided by uDebug.
Please log in to submit your solution.
Difficulty 

Average test runtime  0.20 
Points (changes over time)  10 
Tried by  4 users 
Solved by  4 users 
#  Name  Runtime  Points worth 

1  Justin  0.15  13 
2  贝尔恩德  0.21  9 
3  Irfan  0.21  9 
4  ,s/java/NaN/gi  0.22  9 