CPSed二叉树遍历并不像预期的那样工作

时间:2015-09-24 06:53:00

标签: scheme lisp racket

我的递归版本看起来像

(struct node (val left right) #:transparent)

(define t3 (node 3 '() '()))
(define t4 (node 4 '() '()))
(define t5 (node 5 '() '()))
(define t2 (node 2 t4 t5))
(define t1 (node 1 t2 t3))
;
;     ----- 1 -----
;    |             |
; -- 2 --          3
;|       |
;4       5

(define (countv tree)
  (if (null? tree)
      0
      (+ (node-val tree)
         (countv (node-left tree))
         (countv (node-right tree)))))

(countv t1)

和CPSed版本

(define (countk tree k)
  (if (null? tree)
      (k 0)
      (countk (node-left tree)
              (λ (lval)
                (countk (node-right tree)
                        (λ (rval)
                          (+ (node-val tree) lval rval)))))))

(countk t1 (λ (x) (node-val x)))

countv的结果符合预期15,而countk获得4

1 个答案:

答案 0 :(得分:3)

您忘记将递归结果传递给延续:

(define (countk tree k)
  (if (null? tree)
      (k 0)
      (countk (node-left tree)
              (λ (lval)
                (countk (node-right tree)
                        (λ (rval)
                          (k (+ (node-val tree) lval rval))))))))
                           ^
                          Here

一旦你记住了,你就会得到运行时错误,因为结果不是树 这在您的代码中没有发生,因为您的初始延续从未应用于任何事情。

你应该这样称呼它:

(countk t1 (λ (x) x))