好的,我已经binary search tree
在 OCaml 中编写了一个。
type 'a bstree =
|Node of 'a * 'a bstree * 'a bstree
|Leaf
let rec insert x = function
|Leaf -> Node (x, Leaf, Leaf)
|Node (y, left, right) as node ->
if x < y then
Node (y, insert x left, right)
else if x > y then
Node (y, left, insert x right)
else
node
上面的代码据说很好在OCaml中使用数据结构的正确方法
然而,我发现了一个问题。这insert
仅在一次从列表中构建 bst 时才有效,例如
let rec set_of_list = function
[] > empty
| x :: l > insert x (set_of_list l);;
因此,如果我们不断地从一个列表中构建一个 bst,没问题,我们可以得到一个完整的 bst,其中包含列表中的所有节点。
但是,如果我之前构建了一个 bst,现在我希望插入一个节点,那么生成的 bst 将不会包含上一个树中的完整节点,对吗?
那么我应该如何在 OCaml 中编写一个 bst,以便我们使用前一棵树的所有节点创建一个新的 bst,以保持前一棵树不可变?如果每次我需要从旧 bst 复制所有节点,那会影响性能吗?
编辑:
所以我们一开始就说,一个 bst 是用一个 node 创建的t1 = (10, Leaf, Leaf)
。
然后我做let t2 = insert 5 t1
,然后我得到t2 = (10, (5, Leaf, Leaf), Leaf)
,对吗?在 t2 中,我们给一个变量c1 to the child node (5, Leaf, Leaf)
然后我做let t5 = insert 12 t2
,然后我得到t3 = (10, (5, Leaf, Leaf), (15, Leaf, Leaf))
。让我们给一个变量c2 to the child node (5, Leaf, Leaf)
所以我的问题是是否c1 == c2
?t2 和 t3 中的两个(5, Leaf, Leaf)
s 完全一样吗?