从F#中的二叉搜索树中删除元素

时间:2015-10-30 04:19:43

标签: types f# functional-programming binary-search-tree

我正在尝试编写一个从BST中删除元素的方法。到目前为止,这就是我所拥有的。它几乎可以工作。它适用于要删除的节点有1个子节点以及何时没有子节点,但有2个子节点时我遇到问题。我想用它右边的子树上的最小项替换该节点的值,然后删除其右子树上的最小项,就像普通的BST删除算法一样。

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)
                              rem2 (BinTree(m, lst, rst));; //error in my syntax


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);;

0 个答案:

没有答案