Scheme - 二叉树迭代递归将()作为空节点而不是任何内容附加

时间:2016-03-30 14:14:33

标签: recursion append scheme

我试图编写一个简单的代码,该代码返回"预订"中的树节点值列表。方式。

(define pre-iter  (lambda (tree)
(if (not (pair? tree))
    (list tree)
    (append (list (car tree)) (pre-iter (cadr tree)) (pre-iter (caddr tree)))
)))

我无法找出发生以下情况的原因:

  (iter-tree (quote (F (B A (D C E)) (G () (I H ())))) pre-iter): expected '(F B A D C E G I H), got '(F B A D C E G () I H ())

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

当子树为空时,您只需要处理一个额外的情况。试试这个:

(define pre-iter
  (lambda (tree)
    (cond ((null? tree) '())
          ((not (pair? tree)) (list tree))
          (else
           (append (list (car tree))
                   (pre-iter (cadr  tree))
                   (pre-iter (caddr tree)))))))

按要求运作:

(pre-iter '(F (B A (D C E)) (G () (I H ()))))
=> '(F B A D C E G I H)