我想这个BST有无限循环

时间:2011-04-25 04:17:40

标签: f# tree

我得到的这个代码来自Alexander Battisti,关于如何从数据列表中创建一个树:

let data = [4;3;8;7;10;1;9;6;5;0;2]

type Tree<'a> = 
    | Node of Tree<'a> * 'a * Tree<'a>
    | Leaf

let rec insert tree element = 
    match element,tree with
    | x,Leaf        -> Node(Leaf,x,Leaf)
    | x,Node(l,y,r) when x <= y -> Node((insert l x),y,r)
    | x,Node(l,y,r) when x > y -> Node(l,y,(insert r x))
    | _ -> Leaf


let makeTree = List.fold insert Leaf data

然后我想将此代码实现为我的二叉搜索树代码

let rec BinarySearch tree element = 
    match element,tree with
    | x,Leaf   -> BinarySearch (Node(Leaf,x,Leaf)) x
    | x,Node(l,y,r) when x<=y ->
        BinarySearch l y
    | x,Node(l,y,r) when x>y ->
        BinarySearch r y
    | x,Node(l,y,r) when x=y ->
        true
    | _ -> false

然后我使用我的搜索代码:

> BinarySearch makeTree 5;;

并且结果是none,因为它就像我有一个无限循环 有人能帮我吗?如果我的代码有误,请帮我纠正,谢谢

2 个答案:

答案 0 :(得分:2)

let rec BinarySearch tree element = 
    match tree with
    | Leaf -> false
    | Node(l, v, r) ->
        if v = element then 
            true
        elif v < element then
            BinarySearch r element
        else
            BinarySearch l element


BinarySearch makeTree 5

答案 1 :(得分:2)

Yin的解决方案就是我如何写它。

无论如何,这是一个更接近你的版本的解决方案,并且(希望)解释了出了什么问题:

let rec BinarySearch tree element = 
  match element,tree with
  | x, Leaf   -> 
     // You originally called 'BinarySearch' here, but that's wrong - if we reach
     // the leaf of the tree (on the path from root to leaf) then we know that the
     // element is not in the tree so we return false
     false
  | x, Node(l,y,r) when x<y ->// This needs to be 'x<y', otherwise the clause would be
                              // matched when 'x=y' and we wouldn't find the element!
     BinarySearch l element   // Your recursive call was 'BinarySearch l y' but
                              // that's wrong - you want to search for 'element'
  | x, Node(l,y,r) when x>y ->
      BinarySearch r element
  | x,Node(l,y,r) ->          // You can simplify the code by omitting the 'when' 
      true                    // clause (because this will only be reached when
                              // x=y. Then you can omit the last (unreachable) case