简单的Scheme树深度计数

时间:2016-07-26 22:56:18

标签: tree scheme

我正在简单计划计划中处理问题18.3(页面底部的问题): https://people.eecs.berkeley.edu/~bh/ssch18/trees.html 问题是写入深度,这是一个返回树的最长分支中的节点数的过程。到目前为止,我写了:

(define (depth-count node)
    (cond ((null? (children node))
     1)
    (else
     (reduce + (depth-count (children node)))))

所以我把基础案例作为一个'叶子'节点 - 没有孩子。我希望每个父节点+ 1到一个叶子,然后比较相同深度的节点,并从每个级别获取具有最大值的节点。 我期待写更多的cond子句,它将选择一个分支(最大节点)而不是另一个分支。 我希望递归的案例是一个我可以算的列表......我认为我被困在哪里。 我是以正确的方式来做这件事的吗?任何建议非常感谢。

1 个答案:

答案 0 :(得分:1)

计算节点数,而不是找到最长的分支 - 这与查找树的高度相同。为此,您希望以递归方式查找每个节点的树的最大深度。像这样:

(define (depth-count node)
  (cond ((null? (children node)) 1) ; base case: if node is a leaf
        (else                       ; otherwise node has children
         (add1                                          ; add one
          (apply max                                    ; to the maximum of
                 (map depth-count (children node))))))) ; the recursive call

例如,如果我们将上述过程与给定链接中定义的world-tree一起使用,我们就会得到:

(depth-count world-tree)
=> 4