简体   繁体   中英

Maximum sum of a tree in Scheme

I am having troubles with an exercise I am trying to do because I'm new to this language and to think in a recursive way is kind of hard to me. I have a tree (not neccesary binary) and I need to find the path that gives the maximum sum. For example I have the tree: '(1 ((0) (2 ((3) (2))) (5))) given in the image

Example tree

        1
  0     2     5
      3   2

So I have to do a function: (function '(1 ((0) (2 ((3) (2))) (5)))) and it should return 6 (in this case). There are 2 paths that give the answer: 1 + 2 + 3 = 6 and 1 + 5 = 6. I tried to "translate" a code in python found here , but I have no idea how to do it recursively in Scheme.

The recursion is pretty simple, you just need to check 3 cases:

NUMBER?
NULL?
PAIR?

So in scheme you would structure it like this:

(define (tree-sum t)
  (cond ((number? t)
         ...)
        ((null? t)
         ...)
        ((pair? t)
         ...)))

The pair? one is the recursive case in which you add up the sums of car and cdr. Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM