Search code examples
functionsumbinary-treesml

SML sum of binary tree


I have to write a function which will find a sum of all elements in the binary tree.

Thats how it is defined (tree):

datatype 'a tree= Leaf of 'a | Node of 'a tree * 'a * 'a tree

And I have no idea how should I do it. I admit that I am beginner with SML.

For example: sumTree (Node (Node (Leaf 1, 3, Leaf 2), 7, Leaf 4)) should return 17. sumTree is name of function.

Thanks for help.


Solution

  • I hope you'll take the time to understand this. Let me know if you have any questions regarding it:

    (*
     * This is a recursive datatype, because the Node constructor contains two
     * elements of type `tree`, the type which we're currently defining.
     *)
    datatype 'a tree =
        Leaf of 'a
      | Node of 'a tree * 'a * 'a tree
    
    (*
     * Notice how the structure of the `sumTree` function follows the structure
     * of the `tree` datatype. But `tree` is a recursive datatype, which means
     * that `sumTree` will probably be a recursive function. This is called
     * structural recursion. We recurse accordingly to the structure of the type.
     *)
    fun sumTree (Leaf n) = n
      | sumTree (Node (left, n, right)) = (sumTree left) + n + (sumTree right)
    

    The basic idea is to solve the problem for the easy case (Leaf) and in the complex case (Node) rely on the solution for the easy case.