我创建了一个树ocaml的树简单的功能
type 'a tree = {
mutable cont: 'a;
mutable left: 'a bin_tree;
mutable right: 'a bin_tree
}
and 'a bin_tree =
Empty
| Node of 'a tree;;
,我疲于应付一些简单的功能做这样
- 插入元件(到propper子树,无重复)
- 使两个二叉树的联合
我googled我的问题,但我不断得到错误。例如:
let rec insert x tree =
match tree with
Empty -> Node(x, Empty, Empty)
| Node(y, left, right) ->
if x <= y then Node(y, insert x left, right)
else Node(y, left, insert x right)
,或者如果我尝试:
let rec insert x = function
Empty -> Node(Empty, x, Empty)
| Node(lb, r, rb) -> if x < r then Node(insert x lb, r, rb)
else Node{lb; r; insert x rb} ;;
我经常收到语法错误。
好的,所以我试着插入: 'let rec插入x tree = 匹配树与 空 - > Node {x;空的;空}} |节点{续;剩下; right} - > 如果x <= y,则Node {y;向左插入x; right} else Node {y;剩下;插入x右} ;;' 我不认为这是正确的,虽然 – prima 2013-05-12 13:41:37
至少它可能编译。我无法分辨这是否是您的老师所期望的。他可能希望你保持树木的平衡... – 2013-05-12 13:43:34
树木应该平衡适当,是的。左侧子树包含比节点更小的元素,右侧则包含更大的元素。并且不应该有重复。 – prima 2013-05-12 13:47:04