Stumped with functional breadth-first tree traversal in Clojure?

前端 未结 4 1115
借酒劲吻你
借酒劲吻你 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:41

    Your tree data is incorrect. It should be [1 [2 [4] [5]] [3 [6]]]

    Also, you're mixing the tree traversal with printing and building up a result. Things get simpler if you concentrate on doing the hard part separately:

    (def tree [1 [2 [4] [5]] [3 [6]]])
    

    NOTE THIS IS DEPTH-FIRST. SEE BELOW

    (defn bf "return elements in tree, breath-first"
       [[el left right]] ;; a tree is a seq of one element,
                         ;; followed by left and right child trees
       (if el
         (concat [el] (bf left) (bf right))))
    
    (bf tree)
    => (1 2 4 5 3 6)
    

    CORRECT VERSION

    (defn bf [& roots] 
       (if (seq roots) 
           (concat (map first roots) ;; values in roots
                   (apply bf (mapcat rest roots))))) ;; recursively for children
    
    (bf tree)
    => (1 2 3 4 5 6)
    

提交回复
热议问题