Stumped with functional breadth-first tree traversal in Clojure?

前端 未结 4 1118
借酒劲吻你
借酒劲吻你 2021-02-02 12:24

Say I have a tree defined as per the recommendation in this post, although it\'s a vector in my case, which hopefully shouldn\'t matter (they\'re vectors in Programming Clojure

4条回答
  •  一个人的身影
    2021-02-02 12:53

    Since apparently there is still no breadth-first solution posted, here is a simple algorithm, implemented first eagerly, and then transformed to be lazy:

    (defn bfs-eager [tree]
      (loop [ret [], queue (conj clojure.lang.PersistentQueue/EMPTY tree)]
        (if (seq queue)
          (let [[node & children] (peek queue)]
            (recur (conj ret node) (into (pop queue) children)))
          ret)))
    
    (defn bfs-lazy [tree]
      ((fn step [queue]
         (lazy-seq
          (when (seq queue)
            (let [[node & children] (peek queue)]
              (cons node
                    (step (into (pop queue) children)))))))
       (conj clojure.lang.PersistentQueue/EMPTY tree)))
    

提交回复
热议问题