binary-tree.sml 703 B

12345678910111213141516171819202122232425
  1. (*
  2. A binary tree of elements of generic type 'a is EITHER:
  3. (1) a Leaf carrying a value of type 'a OR
  4. (2) a Node, carrying a tuple of values of the types:
  5. (left) binary tree, containing values of type 'a,
  6. (node value) a value of type 'a,
  7. (right) binary tree containing values of type 'a
  8. *)
  9. datatype 'a btree = Leaf of 'a
  10. | Node of 'a btree * 'a * 'a btree; (* three-arg constructor *)
  11. (* Here is a binary tree *)
  12. val myTree = Node (Leaf 9, 8, Node (Leaf 3, 5, Leaf 7));
  13. (* This function counts the sum of all the elements in a tree *)
  14. fun count (Leaf n) = n
  15. | count (Node (leftTree, n, rightTree)) = count leftTree + n + count rightTree;
  16. val myTreeCount = count myTree;