Recursion 二叉搜索树

Recursion 二叉搜索树,recursion,binary-search-tree,sml,Recursion,Binary Search Tree,Sml,因此,我在SML中为二进制搜索树定义了以下数据类型: datatype tree = Void | Node of tree * int * tree; 我还有这个功能: fun sub_tree a b Void = | sub_tree a b (Node (t1, x, t2)) = if (a <= x) andalso (x < b) then Node ((sub_tree a b t1), x, (sub_tree a b t2))

因此,我在SML中为二进制搜索树定义了以下数据类型:

datatype tree = Void | Node of tree * int * tree;
我还有这个功能:

fun sub_tree a b Void = 
  | sub_tree a b (Node (t1, x, t2)) =
    if (a <= x) andalso (x < b) then
      Node ((sub_tree a b t1), x, (sub_tree a b t2))
    else
      sub_tree a b t2;
因此,该函数在以下情况下工作,例如:

sub_tree 5 8 ex1;
val it =  Node (Node (Void, 5, Void), 6, Node (Void, 7, Void)): tree
但是如果a=0&b=1,它不起作用,因为:

sub_tree 0 1 ex1;
val it = Void: tree
它应该返回:
节点(Void,0,Void)


所以我需要一些帮助来指出我在函数中犯的错误,提前谢谢

您需要在
子树ab(节点(t1,x,t2))中决定三种情况


  • a这几乎就是我所需要的解决方案,但是我测试了它,它没有按照我的预期工作。然而,它让我重新思考了我的函数,我找到了正确的实现:
    如果(a啊,你是对的,我把分割搞糟了:如果
    x>=b
    ,那么这意味着开放间隔
    [a,b[
    可能仍然包含
    t1
    ,但不包含
    x
    t2
    ,另一方面,如果
    x
    间隔不能包含
    t1
    。请参阅编辑版本。
    sub_tree 0 1 ex1;
    val it = Void: tree
    
    if (a <= x) andalso (x < b) then
      Node ((sub_tree a b t1), x, (sub_tree a b t2))
    else if x < a then
      sub_tree a b t2;
    else
      sub_tree a b t1;
    
           a, b <= x       |  a <= x andalso x < b  |       x < a, b
    -----------------------+------------------------+----------------------
      x and t2 are to      |                        |  t1 and x are to
      the right of [a, b[  |  x lies within [a, b[  |  the left of [a, b[
      -> check t1          |  -> check t1 and t2    |  -> check t2