Files
rose-ash/lib/ocaml/baseline/btree.ml
giles 0858986877
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 37s
ocaml: phase 5.1 btree.ml baseline (13/13 pass)
Polymorphic binary search tree with insert + in-order traversal.
Exercises parametric ADT (type 'a tree = Leaf | Node of 'a * 'a tree
* 'a tree), recursive match, List.append, List.fold_left.
2026-05-08 17:52:49 +00:00

26 lines
607 B
OCaml

(* Baseline: binary search tree with insert + in-order traversal *)
type 'a tree =
| Leaf
| Node of 'a * 'a tree * 'a tree
;;
let rec insert x t =
match t with
| Leaf -> Node (x, Leaf, Leaf)
| Node (v, l, r) ->
if x < v then Node (v, insert x l, r)
else if x > v then Node (v, l, insert x r)
else t
;;
let rec inorder t =
match t with
| Leaf -> []
| Node (v, l, r) -> List.append (inorder l) (v :: inorder r)
;;
let from_list xs = List.fold_left (fun t x -> insert x t) Leaf xs ;;
let t = from_list [5; 3; 8; 1; 4; 7; 9; 2] ;;
List.fold_left (fun a b -> a + b) 0 (inorder t)