Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 37s
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.
26 lines
607 B
OCaml
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)
|