I am currently building my binary tree in F#, and I’m almost finished. I’m on the last assignment of this task, where I am supposed to make a string representation of the binary tree. Meaning that the tree should be presented like this:
Example: ("node" "value" ("node" "value" "Empty" "Empty") Empty) <- A tree with a rootnode that has a left subtree with a node that has two empty subtrees, and an empty right subtree.
My tree looks like this:
type Btree<'a when 'a: comparison> =
|Node of 'a * Btree<'a> *Btree<'a>
|Leaf of 'a
|EmptyTree
This is how far I’ve gotten:
let rec treeToString bintree =
match bintree with
|EmptyTree -> "Empty" //Check if the tree is empty
|Node(inner, left, right) when inner = 0 -> "Empty"
|Leaf x-> "Node"+x.ToString() //Returns "Node" and its value
|Node(inner, left, right) when inner <> 0-> treeToString left //Need some kind of output here, but what?
|Node(inner, left, right) when inner <> 0->treeToString right
My method only returns one value, so the actual problem with my solution is getting the recursive part right.
So my question is: What am I doing wrong here?
The union case
Leaf of 'ais redundant becauseLeaf(a)can be modelled byNode(a, Empty, Empty). Type declaration could be simplified to:From the output sample
("node" "value" ("node" "value" "Empty" "Empty") Empty), you should display values of node elements first, then display left branches and right branches recursively:You can push this further by overriding
ToString()methodso that the type works with
sprintf "%O" bintreeand the like.