Skip to content

Commit ada68af

Browse files
author
coderxiang
committed
OCaml 99: binary tree
1 parent cb4d14f commit ada68af

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
(* Collect the nodes at a given level in a list. *)
2+
3+
type 'a binary_tree = Empty | Node of 'a * 'a binary_tree * 'a binary_tree;;
4+
5+
let at_level tr cnt =
6+
let rec at_level_tr tr cnt acc =
7+
match tr with
8+
Empty -> acc
9+
| Node (u, lc, rc) -> begin
10+
if cnt = 1 then List.rev (u :: acc)
11+
else at_level_tr rc (cnt-1) (at_level_tr lc (cnt-1) acc)
12+
end
13+
in
14+
at_level_tr tr cnt []
15+
;;
16+
17+
18+
(* Test *)
19+
let example_tree =
20+
Node('a', Node('b', Node('d', Empty, Empty), Node('e', Empty, Empty)),
21+
Node('c', Empty, Node('f', Node('g', Empty, Empty), Empty)));;
22+
23+
at_level example_tree 10
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
type 'a bst = Empty | Node of 'a * 'a bst * 'a bst;;
2+
3+
let rec construct l =
4+
match l with
5+
[] -> Empty
6+
| x :: xs -> Node (x, construct (List.filter ((>=) x) xs), construct (List.filter ((<)
7+
x) xs))
8+
;;
9+
10+
(* Test *)
11+
construct [3;2;4;7;1]
12+

0 commit comments

Comments
 (0)