Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a direct translation of the <code>bftrav</code> Haskell function from the Wikipedia article. Note that it uses a <code>letrec</code> macro I've just written -- see <a href="http://gist.github.com/486880" rel="nofollow noreferrer">this Gist</a> for the latest version.</p> <p>I've changed your definition of <code>my-tree</code> to read thus:</p> <pre><code>(def my-tree (struct tree 1 (struct tree 2) (struct tree 3 (struct tree 4) (struct tree 5)))) </code></pre> <p>Also, my <code>leaf?</code> function assumes that we're only dealing with proper two-way branches and leaf nodes (so a <code>nil</code> on the <code>:left</code> branch implies a <code>nil</code> on the <code>:right</code> branch); it shouldn't be two difficult to change this to handle single-child "branches":</p> <pre><code>(defn leaf? [t] (nil? (:left t))) </code></pre> <p>The code for <code>bftrav</code> is as follows:</p> <pre><code>(defn bftrav [t] (letrec [queue (lazy-seq (cons t (trav 1 queue))) trav (fn [l q] (lazy-seq (cond (zero? l) nil (leaf? (first q)) (trav (dec l) (rest q)) :else (let [{:keys [left right]} (first q)] (cons left (cons right (trav (inc l) (rest q))))))))] queue)) </code></pre> <p>An example from the REPL:</p> <pre><code>user&gt; (bftrav my-tree) ({:val 1, :left {:val 2, :left nil, :right nil}, :right {:val 3, :left {:val 4, :left nil, :right nil}, :right {:val 5, :left nil, :right nil}}} {:val 2, :left nil, :right nil} {:val 3, :left {:val 4, :left nil, :right nil}, :right {:val 5, :left nil, :right nil}} {:val 4, :left nil, :right nil} {:val 5, :left nil, :right nil}) user&gt; (count (bftrav my-tree)) 5 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload