开发者

UVa #112 Tree Summing

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 i开发者_如何转开发s:

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?


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜