计算树数据结构的深度 - clojure

时间:2015-07-07 09:57:06

标签: clojure s-expression zipper

我试图通过Clojure Zippers实现一个算法来查找序列表达式的深度。

(zip/seq-zip (+ 1 (* 2 3)))

这是我解释要转换为树数据结构的序列的方式。是否有直接的方法通过Zipper库计算这个(从给定的例子中计算为2的深度)?

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:3)

您可以使用以下递归方法:

(defn height [s-expr]
  (if-let [sub-trees (seq (filter coll? s-expr))]
    (inc
     (apply max
            (map height sub-trees)))
    0))


=> (height '(+ 1 (* 2 3)))
=> 1

有效地,上述将集合视为分支,将其他所有内容视为叶子。您可以将coll?替换为符合您需求的任何其他分支定义(例如list?)。

答案 1 :(得分:0)

您可能要计算一棵树的最小和最大高度。 在这种情况下,您可以扩展this approach以包括一个comp函数参数来确定选择标准。

;; Compute the height (either min or max, according to the `comp` function)
;; of the tree `tree`. Trees must be expressed as nested sequences.
(defn height
  [tree comp]
  (if (coll? tree)
    (inc (apply comp (map #(height % comp) tree)))
    0))

(defn max-height [tree] (height tree max))
(defn min-height [tree] (height tree min))
相关问题