【发布时间】:2013-01-04 15:07:55
【问题描述】:
好的,我在 OCaml 中写了一个binary search tree。
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
我猜上面的代码没有问题。
用的时候我写
let root = insert 4 Leaf
let root = insert 5 root
...
这是use/insert 到树的正确方法吗?
我的意思是,我想我不应该声明根并且每次我再次更改变量根的值,对吧?
如果是这样,我怎样才能始终保持根并可以随时向树中插入值?
【问题讨论】:
标签: data-structures functional-programming ocaml