12

For a data type of a binary tree you can write something like this:

data Tree a = Nil | Node a (Tree a) (Tree a)

So if I do want to include trees, with Nodes having more than just two children, how could the data type possibly look like?

1

2 Answers 2

18

A lesser known technique is Left-child right-sibling where you can use the exact same type to encode trees with more than two children per node:

left-child-right-sibiling

data Tree a
  = Nil
  | Node a (Tree a) (Tree a) -- value, left child, right sibling

The alternative [Tree a] does not have a performance advantage, since Haskell lists are linked lists.

Sign up to request clarification or add additional context in comments.

Comments

14

You can either have a fixed branching factor:

data BinaryTree a  = BTNil 
                   | BTNode a (BinaryTree a) (BinaryTree a)

data TernaryTree a = TTNil
                   | TTNode a (TernaryTree a) (TernaryTree a) (TernaryTree a)

data QuadTree a    = QTNil
                   | QTNode a (QuadTree a) (QuadTree a) (QuadTree a) (QuadTree a)

-- etc

(Note that QuadTree isn't a great name for a general tree with a branching factor of 4, since there is a specific data structure with that name.)

or you can simply use a rose tree, which stores an arbitrary list of children at each node.

data RoseTree a = RTNil | RTNode a [RoseTree a]

There is some duplication here, as RTNil is only needed to store an explicit empty tree. Leaf nodes are just RTNode a []. (Consider what difference, if any, you would assign to the values RTNode 3 [], RTNode 3 [RTNil], RTNode 3 [RTNil, RTNil], etc.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.