datatype 'a tree = empty | leaf of 'a | node of 'a * 'a tree * 'a tree;
Max question...
I need help with writing a function using Standard ML NJ. It's using a polymorphic binary tree using this definition for the data type...
datatype 'a tree = empty | leaf of 'a | node of 'a * 'a tree * 'a tree;
And look for the max/min label within that tree. It should take into account an empty tree as well raising an exception but the leaves can be empty...
val myTree = node(1,node(2,leaf 3,empty), node(12,node(4,leaf 5,leaf 11),node(4,leaf 10, leaf 5)))
So...
maxFunc (op < ) tree should return the value 12
maxFunc mytree empty should return "EmptyTree" which is a raised exception
maxFunc (op > ) tree should return the value 1
The function must be polymorphic
Traversal question
For the traversal, I need a binary tree with this definition...
datatype 'a tree = empty | leaf of 'a | node of 'a * 'a tree * 'a tree;
With a traversal helper function that only takes a list and returns the order it needs to be in like this...
fun preorder (x, y, z) = [x] @ y @ z;
But I can't get this to work as a generic function as I'm getting confused with the two functions for the generic function.
getLabels takes a traversal function and a tree, returns a list in the right order. For example...
val tree = node(3,node(2,leaf 4,empty), node(11,node(8,leaf 7,leaf 1) leaf 10);
getLabels postorder tree; would return [4, 2, 3, 7, 8, 1, 11, 10]
getLabels preorder tree; would return [3, 2, 4, 11, 8, 7, 1, 10]
My attempt...
fun getLabels func empty = []
| getLabels func (leaf(x)) = x
| getLabels func (node(internal, left, right)) = let val (node(first, second, third)) = func internal left right
in
getLabels func first @ getLabels func second @ getLabels func third
end;
Functions working separately with expected output but I cannot use this...
fun preorder empty = []
| preorder (leaf(x)) = [x]
| preorder (node(internal, left, right)) = [internal] @ preorder left @ preorder right;
fun postorder empty = []
| postorder (leaf(x)) = [x]
| postorder (node(internal, left, right)) = postorder left @ [internal] @ postorder right;
fun inorder empty = []
| inorder (leaf(x)) = [x]
| inorder (node(internal, left, right)) = inorder left @ inorder right @ [internal];