-
Notifications
You must be signed in to change notification settings - Fork 5
/
tree2.ml
87 lines (71 loc) · 1.84 KB
/
tree2.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
type 'a t =
| Leaf
| Node of 'a t * 'a * 'a t
let rec binsert : 'a -> 'a t -> 'a t =
fun y tree ->
match tree with
| Leaf ->
Node (Leaf, y, Leaf)
| Node (left, x, right) ->
if y == x then
tree
else if y < x then
Node (binsert y left, x, right)
else (* y > x *)
Node (left, x, binsert y right)
let rec pre_order : 'a t -> 'a list =
fun tree ->
match tree with
| Leaf ->
[]
| Node (left, x, right) ->
[x] @ pre_order left @ pre_order right
let rec in_order : 'a t -> 'a list =
fun tree ->
match tree with
| Leaf ->
[]
| Node (left, x, right) ->
in_order left @ [x] @ in_order right
let rec post_order : 'a t -> 'a list =
fun tree ->
match tree with
| Leaf ->
[]
| Node (left, x, right) ->
post_order left @ post_order right @ [x]
let rec count_leaves : 'a t -> int =
fun tree ->
match tree with
| Leaf ->
1
| Node (left, _, right) ->
count_leaves left + count_leaves right
let rec count_nodes : 'a t -> int =
fun tree ->
match tree with
| Leaf ->
0
| Node (left, _, right) ->
1 + count_nodes left + count_nodes right
let rec map : ('a -> 'b) -> 'a t -> 'b t =
fun f tree ->
match tree with
| Leaf ->
Leaf
| Node (left, x, right) ->
Node (map f left, f x, map f right)
let rec count_nodes_at_level : int -> 'a t -> int =
fun level tree ->
if level < 0 then
0
else
match tree with
| Leaf ->
0
| Node (left, _, right) ->
if level = 0 then
1
else
count_nodes_at_level (level - 1) left
+ count_nodes_at_level (level - 1) right