Representing A Tree in Clojure

前端 未结 3 539
挽巷
挽巷 2020-12-28 11:43

What would be an idiomatic way to represent a tree in Clojure? E.g.:

     A
    / \\
   B   C
  /\\    \\
 D  E    F

Performance is not imp

3条回答
  •  Happy的楠姐
    2020-12-28 12:29

    There's a scary way of doing it using just cons:

    (defn mktree 
      ([label l r] (cons label (cons l r))) 
      ([leaf] (cons leaf (cons nil nil))))
    (defn getlabel [t] (first t))
    (defn getchildren [t] (rest t))
    (defn getleft [t] (first (getchildren t)))
    (defn getright [t] (rest (getchildren t)))
    

    Note that children isn't a list; it's a pair. If your trees aren't just binary, you could make it a list. use nil when there's no left or right child, of course.

    Otherwise, see this answer.

    The tree in your picture:

    (mktree 'A (mktree 'B (mktree 'D) (mktree 'E)) (mktree 'C nil (mktree 'F)))
    

提交回复
热议问题