tags:

views:

144

answers:

1

I'm working on UVa #112 Tree Summing. I have what I think should be a working solution but it is not accepted by the online judge due to a basic misunderstanding of the problem on my part. Consider the following inputs:

-1 (-1()())
77 (77(1()())())

or diagrammatically, the trees look like:

  -1              77
 /   \           /  \
()    ()        1    ()
               / \
              ()  ()

According to at least two working solutions, the correct output for the above inputs is:

yes
no

However, I don't understand why the second one should be 'no'. It looks to me like the rightmost path of the tree should give the proper sum. What am I missing?

+1  A: 

Easy.

The tree:

(77(1()())())

A leaf is of this form: (integer () ())

Thus the tree has only one leaf: (1 () ())

The sum of the nodes to this leaf is 78. 78 is not 77. Result: no.

What you think is a rightmost path, is none according to the definition.

The first tree:

(-1()())

It is just a single leaf node. One path. The sum is -1. -1 = -1. Result: yes.

We can check it with a Lisp program:

(defun leaf-p (node)
  "is the node a leaf?"
  (and (= (length node) 3)
       (integerp (first node))
       (null (second node))
       (null (third node))))

(defun path-sums (tree)
  "returns a list of all sums for each path"
  (if (leaf-p tree)
      (list (first tree))
    (mapcar (lambda (s)
              (+ (first tree) s))
            (append (when (second tree)
                      (path-sums (second tree)))
                    (when (third tree)
                      (path-sums (third tree)))))))

(defun tree-sum-p (sum tree)
  (member sum (path-sums tree)))

CL-USER 223 > (path-sums '(-1()()))
(-1)

CL-USER 224 > (path-sums '(77(1()())()))
(78)
Rainer Joswig
But then why is the correct answer for the first example 'yes'? If the rightmost path on the second is none, then both paths of the first should be none.
unclerojelio
@unclerojelio : the first has only a leaf, one path.
Rainer Joswig
Thanks for the help!
unclerojelio