【问题标题】:Simply Scheme tree depth count简单的方案树深度计数
【发布时间】:2016-07-26 22:56:18
【问题描述】:

我正在解决简单方案计划中的问题 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 子句,这些子句将选择一个分支(最大节点)而不是另一个。 我希望递归案例是一个我可以计算的列表......这就是我认为我被卡住的地方。 我会以正确的方式解决这个问题吗?任何建议都非常感谢。

【问题讨论】:

    标签: tree scheme


    【解决方案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
    

    【讨论】:

    • 谢谢,知道了。我忘记了申请。考虑计算深度也很有帮助。非常感谢。
    猜你喜欢
    • 2017-08-13
    • 2019-08-05
    • 1970-01-01
    • 2016-09-13
    • 2011-02-15
    • 1970-01-01
    • 2018-02-13
    • 2022-01-25
    • 2015-02-04
    相关资源
    最近更新 更多