(* Collect the nodes at a given level in a list A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a predicate atlevel/3 to collect all nodes at a given level in a list. % atlevel(T,L,S) :- S is the list of nodes of the binary tree T at level L Using atlevel/3 it is easy to construct a predicate levelorder/2 which creates the level-order sequence of the nodes. However, there are more efficient ways to do that. *) type bin_tree = Leaf of string | Node of string * bin_tree * bin_tree ;; let rec collect_nodes_at_level t l = if l<1 then [] else match t with Leaf(s) -> [] | Node(s,tl,tr) -> List.flatten [ if l=1 then [s] else []; collect_nodes_at_level tl (l-1); collect_nodes_at_level tr (l-1) ] ;;