Skip to content

Instantly share code, notes, and snippets.

@divs1210
Last active November 2, 2022 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divs1210/53cf035349ff9d220e6bb31582338e09 to your computer and use it in GitHub Desktop.
Save divs1210/53cf035349ff9d220e6bb31582338e09 to your computer and use it in GitHub Desktop.
Clojure BFS
(defn BFS [tree]
(loop [roots [tree]
ret []]
(if (empty? roots)
ret
(let [children (->> roots
(mapcat :children)
(remove nil?))
this-level (map :val roots)]
(recur children
(concat ret this-level))))))
;; test
;; ====
(def tree
{:val 1
:children [{:val 2}
{:val 3
:children [{:val 4
:children [{:val 6}]}
{:val 5}]}]})
(BFS tree)
;; => (1 2 3 4 5 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment