Tree Summing
Time Limit: 1000MS |
|
Memory Limit: 10000K |
Total Submissions: 8132 |
|
Accepted: 1949 |
Description
LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, which is the fundamental data structures in LISP, can easily is adapted to represent other important data structur Es such as trees.
This problem deals and determining whether binary trees represented as LISP s-expressions possess a certain property.
Given a binary tree of integers, you is to write a program that determines whether there exists a root-to-leaf path whose Nodes sum to a specified integer. For example, the tree shown below there is exactly four root-to-leaf paths. The sums of the paths are and 18.
Binary trees is represented in the input file as LISP s-expressions have the following form.
Empty tree:: = () tree :: = Empty tree (integer tree)
The tree diagrammed above is represented by the expression (5 (4 (11 (7 ()) (2 () ()) ()) (8 (13 () ()) (4 () (1 () ( )) ) ) )
Note that with this formulation all leaves of a tree is of the form (Integer () ())
Since an empty tree have no root-to-leaf paths, any query as to whether a path exists whose sum are a specified integer in a n Empty tree must be answered negatively.
Input
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 S-expressio N as described above. All binary tree s-expressions is valid, but expressions is spread over several lines and may contain spaces. There would be the one or more test cases in a input file, and input is terminated by End-of-file.
Output
There should is one line of output for each test case (Integer/tree pair) in the input file. For each pair i,t (I represents the integer, T represents the tree) the output was the string yes if there is a Root-to-lea F path in t whose sum is I and no if there are no path in t whose sum is I.
Sample Input
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 ()
Sample Output
Yesnoyesno
Source
Duke Internet programming Contest 1992,uva 112
Give a binary tree expression, ask whether there is a path and is n
AC Code
problem:1145user:kxh1995memory:164ktime:0mslanguage:c++result:accepted
#include <stdio.h>int tree_sum (int n) {int ans=0,m;if (scanf ("(%d", &m)) {ans=tree_sum (n-m) +tree_sum (n-m); if (ans<2) ans=0;} ELSEANS=!N;SCANF (")"); return ans;} int main () {int n;while (scanf ("%d", &n)!=eof) {if (Tree_sum (n)) printf ("yes\n"); elseprintf ("no\n");}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ Topic 1145/uva topic, summing (binary tree traversal)