【发布时间】:2016-01-30 10:37:02
【问题描述】:
我正在尝试编写一种从 BST 中删除元素的方法。到目前为止,这就是我所拥有的。我不确定我是否走在正确的轨道上,或者是否有更好的方法可以通过使用模式匹配来匹配不同的删除案例,即:没有孩子、1 个孩子、2 个孩子。
type 'a bst = NL | BinTree of 'a * 'a bst * 'a bst;;
let rec smallest = function
| NL -> failwith "tree is empty"
| BinTree(m, lst, rst) -> if lst = NL then BinTree(m, lst, rst)
else smallest lst;;
let rec smallest2 = function
| NL -> failwith "tree is empty"
| BinTree(m, lst, rst) -> if lst = NL then m
else smallest2 lst;;
let rec rem2 = function
| NL -> NL
| BinTree(m, NL, NL) -> NL
| BinTree(m, NL, rst) -> rst
| BinTree(m, lst, NL) -> lst
| BinTree(m, lst, rst) -> BinTree(smallest2 rst, lst, rst);;
let rec rem x = function
|NL -> failwith "Node doesn't exit"
|BinTree(m, lst, rst) -> if m = x then rem2 (BinTree(m, lst, rst))
elif m < x then BinTree(m, lst, rem x rst)
else BinTree(m, rem x lst, rst);;
没有子节点和单子节点的情况完美运行,但是当要删除的节点有2个子节点时,我不知道如何实现这种情况。我想用它的右子树上的最小项替换该节点的值,然后删除其右子树上的最小项。
【问题讨论】:
-
你有什么问题?
标签: types f# binary-search-tree